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"]
树的遍历,相当简单,OnePass
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private List<String> helper(TreeNode root, List<String> list, String str){
if(root == null) return list;
if(root.left == null && root.right == null){
list.add(str+root.val);
return list;
}
helper(root.left, list, str+root.val+"->");
helper(root.right, list, str+root.val+"->");
return list;
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> list =new ArrayList<>();
return helper(root, list, "");
}
}