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

后端 未结 3 1205
隐瞒了意图╮
隐瞒了意图╮ 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:17

    Assuming you only need to solve the problem once (per data set) then a simple approach is to collect the set of ancestors from one node (along with itself), and then walk the list of ancestors from the other until you find a member of the above set, which is necessarily the lowest common ancestor. Pseudocode for that is given:

    Let A and B begin as the nodes in question.
    seen := set containing the root node
    while A is not root:
        add A to seen
        A := A's parent
    while B is not in seen:
        B := B's parent
    B is now the lowest common ancestor.
    

    Another method is to compute the entire path-to-room for each node, then scan from the right looking for a common suffix. Its first element is the LCA. Which one of these is faster depends on your data.

    If you will be needing to find LCAs of many pairs of nodes, then you can make various space/time trade-offs:

    You could, for instance, pre-compute the depth of each node, which would allow you to avoid re-creating the sets(or paths) each time by first walking from the deeper node to the depth of the shallower node, and then walking the two nodes toward the root in lock step: when these paths meet, you have the LCA.

    Another approach annotates nodes with their next ancestor at depth-mod-H, so that you first solve a similar-but-H-times-smaller problem and then an H-sized instance of the first problem. This is good on very deep trees, and H is generally chosen as the square root of the average depth of the tree.

提交回复
热议问题