My Java Solution using DFS. No global list variable used.


  • 0
    M

    My Java Solution using DFS. No global list variable used.

    public List<String> binaryTreePaths(TreeNode root) {
            
            List<String> rootToLeafPaths = new ArrayList<String>();
            
            if (root == null) {
                return rootToLeafPaths;
            }
            
            /*List<String> leftSubTreePaths = binaryTreePaths(root.left);
            
            if (leftSubTreePaths != null) {
                rootToLeafPaths.addAll(leftSubTreePaths);
            }
            
            List<String> rightSubTreePaths = binaryTreePaths(root.right);
            
            if (rightSubTreePaths != null) {
                rootToLeafPaths.addAll(rightSubTreePaths);
            }*/
            
            rootToLeafPaths.addAll(binaryTreePaths(root.left));
            rootToLeafPaths.addAll(binaryTreePaths(root.right));
            
            if (rootToLeafPaths.size() == 0) {
                rootToLeafPaths.add("" + root.val);
            } else {
                for (int i=0; i < rootToLeafPaths.size(); i++) {
                    rootToLeafPaths.set(i, root.val + "->" + rootToLeafPaths.get(i));
                }
            }
            
            return rootToLeafPaths;
        }
    

Log in to reply
 

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