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
Below is the solution using recurssion. We perform a in order traversal of the binary tree, as we move down a level we sum up the total path weight by adding the weight of the current level to the weights of previous levels of the tree, if we hit our sum we then print out the path. This solution will handle cases where we may have more than 1 solution along any given path path.
Assume you have a binary tree rooted at root.
#include
#include
using namespace std;
class Node
{
private:
Node* left;
Node* right;
int value;
public:
Node(const int value)
{
left=NULL;
right=NULL;
this->value=value;
}
void setLeft(Node* left)
{
this->left=left;
}
void setRight(Node* right)
{
this->right = right;
}
Node* getLeft() const
{
return left;
}
Node* getRight() const
{
return right;
}
const int& getValue() const
{
return value;
}
};
//get maximum height of the tree so we know how much space to allocate for our
//path vector
int getMaxHeight(Node* root)
{
if (root == NULL)
return 0;
int leftHeight = getMaxHeight(root->getLeft());
int rightHeight = getMaxHeight(root->getRight());
return max(leftHeight, rightHeight) + 1;
}
//found our target sum, output the path
void printPaths(vector& paths, int start, int end)
{
for(int i = start; i<=end; i++)
cerr<& paths, int depth, const int sum)
{
//base case, empty tree, no path
if( root == NULL)
return;
paths[depth] = root->getValue();
int total =0;
//sum up the weights of the nodes in the path traversed
//so far, if we hit our target, output the path
for(int i = depth; i>=0; i--)
{
total += paths[i];
if(total == sum)
printPaths(paths, i, depth);
}
//go down 1 level where we will then sum up from that level
//back up the tree to see if any sub path hits our target sum
generatePaths(root->getLeft(), paths, depth+1, sum);
generatePaths(root->getRight(), paths, depth+1, sum);
}
int main(void)
{
vector paths (getMaxHeight(&root));
generatePaths(&root, paths, 0,0);
}
space complexity depends on the the height of the tree, assumming this is a balanced tree then space complexity is 0(log n) based on the depth of the recurssion stack. Time complexity O(n Log n) - based on a balanced tree where there are n nodes at each level and at each level n amount of work will be done(summing the paths). We also know the tree height is bounded by O(log n) for a balanced binary tree, so n amount of work done for each level on a balanced binary tree gives a run time of O( n log n)