Recursive Java solution


  • 0
    T
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> paths = new ArrayList<String>();
            computePaths(root, paths, "");
            return paths;
        }
        
        public void computePaths(TreeNode n, List<String> paths, String currentPath){
            if(n == null){
                return;
            }
            
            if(currentPath.length() == 0){
                currentPath = ""+n.val;
            } else {
                currentPath = currentPath + "->" + n.val;
            }
            
            if(n.left == null && n.right == null){
                paths.add(currentPath);
                return;
            } else {
                computePaths(n.left, paths, currentPath);
                computePaths(n.right, paths, currentPath);
            }
        }
    }
    

Log in to reply
 

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