Java solution (using Preorder Traversal )


  • 0
    N
    public class Solution {
    
    boolean ans = false;
    
    public boolean hasPathSum(TreeNode root, int sum) {
        
        if(root==null)
            return false;
            
        searchTree(root , 0 ,sum) ;
        
        return ans;
        
    }
    
    public void searchTree( TreeNode root, int preSum , int sum){
        
        int nowSum = root.val + preSum;
        
        if(root.left==null && root.right==null && nowSum==sum )//if to the leaf, check is the path equals the given sum 
            ans = true ;
            
        if(root.left!=null) 
            searchTree( root.left, nowSum , sum);
            
        if(root.right!=null)
            searchTree( root.right, nowSum , sum);
        
    }
    

    }


Log in to reply
 

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