Wednesday, July 12, 2006

Distance[1]

/***
You are given 2 pointers to two nodes (p1, p2) in a binary search tree. Devise an algorithm to find the distance between p1 and p2 (i.e. the length of the shortest path between them).
***/
take ln as the lowest value node, and hn as the high value node,cn has the current node

Node cn=ln;
int c=0;
while (cn != root && cn.parent < hn)
cn = cn.parent
c++;
endwhile
while (cn != hn)
cn = cn > hn ? cn.left : cn.right;
c++;
endwhile

No comments: