The following is an interview question.
You are given a binary tree (not necessarily BST) in which each node contains a value. Design an algorithm t
Since we need the paths having sum == k . I assume worst case complexity can be O(total_paths_in_tree) .
So why not generate every path and check for the sum , anyways it is a tree having negative numbers and is not even a binary search tree .
struct node{
int val;
node *left,*right;
node(int vl)
{
val = vl;
left = NULL;
right = NULL;
}
};
vector > all_paths;
vector > gen_paths(node* root)
{
if(root==NULL)
{
return vector > ();
}
vector > left_paths = gen_paths(root->left);
vector > right_paths = gen_paths(root->right);
left_paths.push_back(vector ()); //empty path
right_paths.push_back(vector ());
vector > paths_here;
paths_here.clear();
for(int i=0;i vec;
vec.clear();
vec.insert(vec.end(), left_paths[i].begin(), left_paths[i].end());
vec.push_back(root->val);
vec.insert(vec.end(), right_paths[j].begin(), right_paths[j].end());
paths_here.push_back(vec);
}
}
all_paths.insert(all_paths.end(),paths_here.begin(),paths_here.end());
vector > paths_to_extend;
paths_to_extend.clear();
for(int i=0;ival);
}
for(int i=0;ival);
}
return paths_to_extend;
}
For generating paths I have generated all left paths and all right paths And added the left_paths + node->val + right_paths to all_paths at each node. And have sent the paths which can still be extended .i.e all paths from both sides + node .