Java Clean Solution


  • 0
    public class Solution {
        
        private void buildPaths(TreeNode node, boolean isRoot, String path, List<String> paths) {
            String newPath = isRoot ? path+node.val : path+"->"+node.val;
            if(node.left == null && node.right == null)
                paths.add(newPath);
            if(node.left != null)
                buildPaths(node.left,false,newPath,paths);
            if(node.right != null)
                buildPaths(node.right,false,newPath,paths);
        }
        
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> paths = new ArrayList<String>();
            if(root != null)
               buildPaths(root,true,"",paths);
            return paths;
        }
    }

Log in to reply
 

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