257. 二叉树的所有路径
原题
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {private List<String> ans = new ArrayList<>();public List<String> binaryTreePaths(TreeNode root) {if(root==null){return ans;}dfs(root,"");return ans;}public void dfs(TreeNode node,String str){//为叶子结点if(node.left==null&&node.right==null){str = str + node.val;ans.add(str);return;}str = str + node.val + "->" ;//遍历左子树if(node.left!=null){dfs(node.left,str);}//遍历右子树if(node.right!=null){dfs(node.right,str);}}
}