Lowest Common Ancestor of Binary Tree(Not Binary Search Tree)

后端 未结 3 1216
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 16:08

I tried working out the problem using Tarjan\'s Algorithm and one algorithm from the website: http://discuss.techinterview.org/default.asp?interview.11.532716.6, but none is

3条回答
  •  臣服心动
    2021-01-03 16:24

    The LCA algorithm tries to do a simple thing: Figure out paths from the two nodes in question to the root. Now, these two paths would have a common suffix (assuming that the path ends at the root). The LCA is the first node where the suffix begins.

    Consider the following tree:

                  r * 
                   / \
                s *   *
                 / \
              u *   * t
               /   / \
              * v *   *
                 / \
                *   *
    

    In order to find the LCA(u, v) we proceed as follows:

    • Path from u to root: Path(u, r) = usr
    • Path from v to root: Path(v, r) = vtsr

    Now, we check for the common suffix:

    • Common suffix: 'sr'
    • Therefore LCA(u, v) = first node of the suffix = s

    Note the actual algorithms do not go all the way up to the root. They use Disjoint-Set data structures to stop when they reach s.

    An excellent set of alternative approaches are explained here.

提交回复
热议问题