Jun 11, 2009

Given a value and a binary search tree. Print all the paths(if there exists more than one) which sum up to that value. It can be any path in the tree.

Given a value and a binary search tree.
Print all the paths(if there exists more than one) which sum up to that
value. It can be any path in the tree. It doesn't have to be from the root.
foo(tree* root, vector vals)
{
if(!root) return;

vals.push(root->val);
if(!root->left&&!root->right)
bar(vals, k);

foo(root->left,vals);
foo(root->right,vals);
}
bar(vector vals, int k)
{
int p1=0;
int p2=1;
int sum=vals[p1]+vals[p2];
while(p2 {
if(sum>=k)
{
if(sum==k) print(vals[p1],vals[p2]);
p1++;
}
else
sum+=vals[++p2];
}
}

No comments:

Post a Comment