[LeetCode/LintCode] Binary Tree Paths

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 binaryTreePaths(TreeNode root) {
        // Write your code here
        List res = new ArrayList();
        if (root == null) {
            return res;
        }
        findpaths(root, res, root.val + "");// +"" String
        return res;
    }
    public void findpaths(TreeNode root, List 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 binaryTreePaths(TreeNode root) {
        List res = new ArrayList<>();
        if (root == null) return res;
        dfs(root, "", res);
        return res;
    }
    private void dfs(TreeNode root, String str, List 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);
    }
}

좋은 웹페이지 즐겨찾기