Write a function that checks whether a path with given sum exists in the tree.
Difficulty level
This exercise is mostly suitable for students
int pathwithsum(Btree B, int sum)
{
int remaining;
if(!B)
return sum==0;
remaining = sum - B->data;
if(B->left && B->right || !B->left && !B->right)
return pathwithsum(B->left, remaining) || pathwithsum(B->right, remaining);
else
if(B->left)
return pathwithsum(B->left, remaining);
else
return pathwithsum(B->right, remaining);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Kruskal Algorithm - Minimal Spanning Tree