I am searching a non recursive algorithm version of finding the least common ancestor in a sorted binary tree written in Java. Everything I found is only the recursive version (even on stackoverflow and on other websites).
Can some one write or direct me to the non recursive version (using while loop)? Also write if this version is more efficient in terms of time complexity?
Just happened to see this long forgotten question.
Do you mean something like, if you are given a tree:
something like that?
2 methods to give (all assume the provided nodes are in the tree):
If there are link to parent (i.e. you are pointing from B back to A), then solution is easy, similar to finding intersecting linked list:
find depth of Node1 and Node2, assuming the depth is
D1
andD2
. Find the difference betweenD1
andD2
(assumingd
). Have pointer to Node1 and Node2 (assume p1 and p2). For the node with higher depth, navigate to parent d-th times. At this point,p1
andp2
will have same depth beneath the ancestor. Just have a simple loop to navigate bothp1
andp2
to parent, until you hit the node thatp1 == p2
.If no parent link in node, you can iteratively navigate the tree:
The basic idea is, given it is a binary search tree, if two nodes are both larger / smaller than current node, it will goes to same child tree. So the common ancestor is the node that two values goes to different children, i.e. when one is smaller than current node and the other one is larger.