Recursive Java Solution (Easy to Understand)


  • 0

    """

    //we start from the root, every time we decide to move left or right if it exists:

      public boolean hasPathSum(TreeNode root, int sum){
    
        if(root==null) return false;
        //we move to the leaf 
        if(sum==root.val&&root.left==null&&root.right==null) 
        return true;
        if(root.left!=null||root.right!=null) 
        return (hasPathSum(root.left,sum-root.val)
        ||hasPathSum(root.right,sum-root.val));
        return false;
        
    }
    

    """


Log in to reply
 

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