Looking for fast algorithm to find distance between two nodes in binary tree

后端 未结 7 2052
渐次进展
渐次进展 2020-12-31 05:03

How do I find the distance between two nodes in a binary tree? Equivalently, what algorithms are there for finding the most recent common ancestor (lowest common ancestor)

7条回答
  •  梦谈多话
    2020-12-31 05:22

    First, search for the height of the first element. Also, return the path to get there using a linked list. You can do this in O(logN) time . Assume tree is balanced, where height is logN. let H1 = height of first element.

    Then, search for the heigh to the second element. Also, return the path to get there using a linked list. You can do this in O(logN) time. Let H2 = height of second element.

    Trace through both linked list collected until the values are no longer equal (paths diverge) The point before they diverge, call the height of that node H3.

    Thus, the longest path is H1 + H2 - 2*H3 (since you need H1 to go to H1, and H2 to go to H2. But really, you can trace back from H1 up till H1-H3. and then move to H2 from H3. So it's (H1-H3) + (H2-H3) = H1+H2 -2*H3.

    Implementation details should be straight forward

    search(Tree* Head, Node* Value, LinkedList path, int distance); 
    

    Thus,

    search(Head, Value1, path1, height1); 
    search(Head, Value2, path2, height2); 
    
    i = 0; 
    while (path1[i] == path2[i])
    {
        i++; 
    }
    height3 = i-1; 
    return height1+height2- 2*height3; 
    

    Time Complexity: O(logN)+ O(logN) + O(logN) = O(logN) Space Complexity: O(logN) (to store both linked list of distances)

提交回复
热议问题