My java answer ( using Preorder Traversal )


  • 1
    N

    public class Solution {

    List<String> paths = new ArrayList<String>(); 
    String curPath = ""; 
    
    public List<String> binaryTreePaths(TreeNode root) {
        
        if(root==null){
            return paths ;
        }
        
        searchTree(root,curPath);
        
        return paths ;
        
        
    }
    
    public void searchTree(TreeNode root,String curPath){
        
      
        curPath += root.val ;
        
        
        // add curPath to paths
        if(root.left==null && root.right==null){
    
            paths.add(curPath);
            
            return ;
            
        }
        
        curPath += "->" ; 
            
        if(root.left != null)
            searchTree(root.left,curPath);
            
        if(root.right != null)    
            searchTree(root.right,curPath);
        
    }
    

    }


Log in to reply
 

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