Least common ancestor search in binary tree non recursive version - Java

南楼画角 提交于 2019-12-08 18:11:23

Just happened to see this long forgotten question.

Do you mean something like, if you are given a tree:

       A
   B       C
 D   E   F   G
H I J K L M N O

commonAncestor(L,G) = C
commonAncestor(H,O) = A
commonAncestor(B,H) = B

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 and D2. Find the difference between D1 and D2 (assuming d). 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 and p2 will have same depth beneath the ancestor. Just have a simple loop to navigate both p1 and p2 to parent, until you hit the node that p1 == p2.


If no parent link in node, you can iteratively navigate the tree:

currentNode = root;
while (true) {
    if ((currentNode > node1 && currentNode < node2) ||
        (currentNode < node1 && currentNode > node2)) {
        break;  // current node is the common ancestor, as node1 and node2 
                // will go to different sub-tree
    } else if (currentNode > node1) {
        currentNode = currentNode.left;
    } else { // currentNode < node1/2
        currentNode = currentNode.right;
    }
}

// currentNode will be the answer you want

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!