Dec 27, 2008

Given 2 nodes in a binary tree (not a binary search tree), find the first common parent node. You are not allowed to store any nodes in a data structu

Given 2 nodes in a binary tree (not a binary search tree), find the first common parent node. You are not allowed to store any nodes in a data structure.
Solution: find two heights, each of which from root to one node, get the difference (diff) of two heights, upward the node with longer height diff steps, then upward two nodes one step at each time, until you get the common node.

struct Tree{
int val;
struct Tree* p;
struct Tree* l;
struct Tree* r;
};
typedef struct Tree tree;


tree* foo(tree* root, tree* n1, tree* n2)
{
if(!root||!n1||!n2) return NULL;
int h1=h2=0;
tree* c1=n1;
tree* c2=n2;

while(c1!=root)
{
h1++;
c1=c1->p;
}
while(c2!=root)
{
h2++;
c2=c2->p;
}
while(n1!=n2)
{
if(h1>h2){n1=n1->p;h1--;}
else if(h2>h1){n2=n2->p;h2--;}
else {n1=n1->p; n2=n2->p;h1--;h2--;}
}
return n1;
}

No comments:

Post a Comment