Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
>
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> allPaths=new ArrayList<String>();
if(root==null) return allPaths;
if(root.left==null&&root.right==null){//容易忽略
allPaths.add(root.val+"");//将int转为string
return allPaths;
}
List<String> left=binaryTreePaths(root.left);
List<String> right=binaryTreePaths(root.right);
for(String item1:left){
item1=root.val+"->"+item1;
allPaths.add(item1);//不能再外面加
}
for(String item2:right){
item2=root.val+"->"+item2;
allPaths.add(item2);//不能再外面加
}
return allPaths;
}
}