# Beginner's question

This is a discussion on Beginner's question within the C Programming forums, part of the General Programming Boards category; Here's a sample code I came up for the following question : Given a tree and a sum, return true ...

1. ## Beginner's question

Here's a sample code I came up for the following question :

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.

Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*

Code:
```int subsums (TREE T, int sum){

if (T==NULL){
return (sum);
}
else{
int subsum = sum - T->element;
return (subsums(T->left, subsum) && subsums(T->right, subsum));
}// else
}```

if sum!=0 why is the result always printed as 1?
int => it should print any value right? or does is convert to boolean ?

2. ## Can any one please explain this

For the same question above, the solution given was:

Code:
```int hasPathSum(struct tree_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->element;
return(hasPathSum(node->left, subSum) ||
hasPathSum(node->right, subSum));
}
}```
I don't understand how if (node ==NULL) return (sum ==0) checks the logic (if sum == 0). Any help is greatly appreciated.

3. The best thing to do in this case I think would be to take a sheet a paper, draw a tree on it, and run the algorithm by hand. You'll see what the NULL part if for.

Basically, it checks that, once you reached a leaf, the accumulated sum is equal to the sum you began with.