Where am I wrong?


  • 0
    9
        bool hasPathSumPre(TreeNode* root, int sum){
    	if (root == NULL) return sum == 0;
    	return hasPathSumPre(root->left, sum - root->val) || hasPathSumPre(root->right, sum - root->val);
    }
    
    bool hasPathSum(TreeNode* root, int sum) {
    	if (root == NULL) return false;
    	return hasPathSumPre(root, sum);
    }

  • 1
    M

    Well, I think the problem may come from ROOT TO LEAF PATH. you have to make sure that when sum == 0, the node should be a leaf.
    suppose we have a tree like

    1
     \
      2
    

    and sum is 1.
    your code will return true because root.left will return true.


Log in to reply
 

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