print all the paths of BT, the out put format should be: [“1->2->5”, “1->3”]
clearly, we will use the preorder, but they are not exactly the same.
I can’t think of any ways to get this problem done.
but based on the solution:
binaryTreePath(root) = searchBt(root, String path, List answer) = searchBT(root.left, path+root.val+"->", answer) searchBT((root.right, path+root.val+"->", answer) //and when it reached the end, we added the current path to our list.
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if (root == null) return list;
helper(root, list, ""); //root, 返回集合,返回集合中的子元素
return list;
}
private void helper(TreeNode cur, List<String> list, String path) {
if (cur.left == null && cur.right == null) {
list.add(path + cur.val);
return;
}
if (cur.left != null) helper(cur.left, list, path + cur.val + "->");
if (cur.right != null) helper(cur.right, list, path + cur.val + "->");
}
}
有的时候 用helper函数也并不好 因为这个函数名太不直观 写递归等式的时候很难理解。
而且还有一点 root == null这个条件一定要判断。