*Java* Easy to understand solution 3-line DFS


  • 8
    E

    Code in Java:

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>(); // stores the final output
        if(root==null) return res;
        helper(root, "", res);
        return res;
    }
    // DFS
    private void helper(TreeNode root, String str, List<String> res) {
        if(root.left==null && root.right==null) res.add(str + root.val); // reach a leaf node, completes a path
        if(root.left!=null)                     helper(root.left, str+root.val+"->", res); // recursively checks its left child
        if(root.right!=null)                    helper(root.right, str+root.val+"->", res); // recursively checks its right child
    }
    

    If you are interested in my other posts, please feel free to check my Github page here: [https://github.com/F-L-A-G/Algorithms-in-Java][1]
    [1]: https://github.com/F-L-A-G/Algorithms-in-Java


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.