Recursive java solution - 4ms - Requesting suggestions on improving performance


  • 0
    K

    This is a straight forward approach where I traverse through the tree DFS-wise and return the list while backtracking. Please suggest if this is not a good approach.

    public List<String> binaryTreePaths(TreeNode root) {
            List<String> paths = new ArrayList<String>();
            if(root==null) return paths;
            List<String> leftPaths= binaryTreePaths(root.left);
            List<String> rightPaths= binaryTreePaths(root.right);
            if(!leftPaths.isEmpty() || !rightPaths.isEmpty()){
                for(String left : leftPaths)
                    paths.add(root.val+"->"+left);
                for(String right : rightPaths)
                    paths.add(root.val+"->"+right);
            }
            else
                paths.add(root.val+"");
            return paths;
        }

Log in to reply
 

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