Binary Tree Paths

public class Solution {
    /**
     * @param root the root of the binary tree
     * @return all root-to-leaf paths
     */
    public List<String> binaryTreePaths(TreeNode root) {
        // Write your code here
        if(root != null) findPaths(root,String.valueOf(root.val));
        return res;
    }

    private void findPaths(TreeNode n, String path){
        if(n.left == null && n.right == null) res.add(path);
        if(n.right != null) findPaths(n.right, path+"->"+n.right.val);
        if(n.left != null) findPaths(n.left, path+"->"+n.left.val);
        
    }

    private List<String> res = new ArrayList();
}

最后更新于

这有帮助吗?