SImple Java Solution | 4 ms


  • 0
    S
        public List<String> binaryTreePaths(TreeNode root) {
            
            if(root == null) return new ArrayList<String>();
            return path(root,"",true);
        }
        
        
        public ArrayList<String> path(TreeNode root, String pathSoFar,boolean isroot){
            
            ArrayList<String> returnResult = new ArrayList<String>();
            if(root == null ) return null;
            
            String pathNode = "";
            if(isroot){
                pathNode = ""+root.val;
            }else{
                pathNode = pathSoFar+"->"+root.val;
            }
            
            if(root.left == null && root.right == null) {
                returnResult.add(pathNode);
                return returnResult;
            }
            if(root.left != null){
                ArrayList<String> left = path(root.left,pathNode,false);
                if(left!=null) returnResult.addAll(left);
            }
            if(root.right != null){
                ArrayList<String> right = path(root.right,pathNode,false);
                if(right!=null) returnResult.addAll(right);
            }
            
            return returnResult;
        }
    }```

Log in to reply
 

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