Lowest Common Ancestor Algorithm

前端 未结 6 1837
感动是毒
感动是毒 2021-02-05 17:42

So I have been looking into implementing a lowest common ancestor algorithm. I looked at many different algorithms (mainly variations of Trajan\'s solution or variations of the

6条回答
  •  遇见更好的自我
    2021-02-05 18:13

    For a tree that small, I wouldn't bother implementing anything more complex. Your solution looks good, although the time complexity is squared in terms of the height of the tree. If you can easily implement a Set (most languages have it built-in), then the algorithm could be tweaked to,

    1. Traverse from the first node up to the root and collect all nodes in a set
    2. Traverse from the second node up to the root and check if the current node exists in that set. If it does, then that is the common ancestor.

    Also, this algorithm assumes that a node can be its own ancestor. Otherwise, you would have to tweak the algorithm slightly. Consider this example,

    A
    |
    B
    |
    C
    

    When trying to find the lowest common ancestor of B, and C, this algorithm would report B, which may or may not be true depending on how you define ancestor.

提交回复
热议问题