Amazon Interview Question
Country: United States
Assuming a binary tree, the solution should look like the following:
1. find the difference between the heights of the two nodes. (diff)
2. depending upon the difference in height, change the pointer to the node, such that, both the pointers are at the same depth.
3. While the pointers do not point at the same node, keep assigning the pointer to the parent of the current node. Also, keep counting the steps (d_factor).
4. Total Distance = ( 2 * d_factor) + diff
Here's the code snippet:
----
d1 = depthOf(n1);
d2 = depthOf(n2);
diff = d1 - d2;
if ( d1 > d2 )
{
for ( int i = 0 ; i < diff; i++ )
n1 = n1->parent;
}
else
{
for ( int i = 0 ; i < diff; i++ )
n2 = n2->parent;
}
dist_factor = 0;
while ( node1 != node2 )
{
node1 = node1->parent;
node2 = node2->parent;
dist_factor++;
}
totalDistance = (2 * dist_factor) + diff;
--
Probably find lca of n1 and n2. Now, find the path length from lca from n1 and n2 and sum it.
- Anonymous October 28, 2012