Problem

Given a binary tree, return all root-to-leaf paths.

Example

Given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

[
  "1->2->5",
  "1->3"
]

Solution

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        // Write your code here
        List<String> res = new ArrayList<String>();
        if (root == null) {
            return res;
        }
        findpaths(root, res, root.val + "");//这里+""巧妙地调用了String
        return res;
    }
    public void findpaths(TreeNode root, List<String> res, String cur) {
       
        if (root.left != null) {
           findpaths(root.left, res, cur + "->" + root.left.val);
        }
        if (root.right != null) {
           findpaths(root.right, res, cur + "->" + root.right.val);
        }
        if (root.left == null && root.right == null) {
           res.add(cur);
           return;
        }
    }
}

###Update 2018-9

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) return res;
        dfs(root, "", res);
        return res;
    }
    private void dfs(TreeNode root, String str, List<String> res) {
        if (root.left == null && root.right == null) res.add(str+root.val);
        
        if (root.left != null) dfs(root.left, str+root.val+"->", res);
        if (root.right != null) dfs(root.right, str+root.val+"->", res);
    }
}

linspiration
161 声望53 粉丝