This is the problem statement:
"Given a tree and a sum, return true if there is a path from the root down to a leaf, such that adding up all the values along the path equals the given sum."
I implemented it like this:
int hasPathSum(Node* node, int sum) {
if(node == NULL)
return sum == 0;
int diff = sum - node->data;
if(diff < 0) return 0;
if(diff == 0)
return node->left == NULL && node->right == NULL ? 1 : 0;
if(diff < node->data)
return hasPathSum(node->left, diff);
else
return hasPathSum(node->right, diff);
}
I only traverse 1 sub-tree and not both, depending on the difference of (sum - node->data)
.
However, the recommended solution required traversing both the subtrees like this:
int hasPathSum(Node* node, int sum) {
// return true if we run out of tree and sum==0
if (node == NULL) {
return(sum == 0);
}
else {
// otherwise check both subtrees
int subSum = sum - node->data;
return(hasPathSum(node->left, subSum) ||
hasPathSum(node->right, subSum));
}
}
I don't see why do we have to traverse both the subtrees ?
Here is the source of the problem: Problem 7
EDIT:
Bad assumption on my part that the tree is a BST. Its just a binary tree.
However, if it were a BST, I'd like to hear some feedback on my implementation ? Would it not be better to do it the way I did it than the other solution ? (which is a little unfair to compare since that solution is for any binary tree)
EDIT solution:
Please see anatolyg's response here which explains the problem with my proposed solution. Thanks anatolyg.