Easy to understand Recursive Java solution


  • 0
    T
    public boolean hasPathSum(TreeNode root, int sum) {
    
        if( root == null ) return false;
        int count = 0;
        return helper(root,count,sum);
    }
    
    private boolean helper(TreeNode node, int count, int sum){
    
        if( node == null ){
            return count==sum;
        }
        if( node.left == null ){
            return helper(node.right,count+node.val,sum);
        }
        else if( node.right == null ){
            return helper(node.left, count+node.val, sum);
        }
    
        return helper(node.left,count+node.val, sum) || helper(node.right, count+node.val, sum);
    }

Log in to reply
 

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