2ms Java recursive solution with explaination


  • 6
    C

    The idea is to perform a dfs, for every node we visit the path up till that node is path + currentNode.val and when we see that a node has no children we know this is one of the valid path.

     public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        helper(root, result, "");
        return result;
    }
    public void helper(TreeNode root, List<String> result, String path){
        if(root == null){
            return;
        }
        if(root.left == null && root.right == null){
            result.add(path+root.val);
            return;
        }
        
        helper(root.left, result, path+root.val+"->");
        helper(root.right, result, path+root.val+"->");
        return;
    }

Log in to reply
 

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