Lowest Common Ancestor of a Binary Tree

后端 未结 6 442
栀梦
栀梦 2021-02-02 00:01

This is a popular interview question and the only article I can find on the topic is one from TopCoder. Unfortunately for me, it looks overly complicated from an interview answe

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-02 00:53

    It matters what kind of tree you are using. You can always tell if a node is the ancestor of another node in constant space, and the top node is always a common ancestor, so getting the Lowest Common Ancestor in constant space just requires iterating your way down. On a binary search tree this is pretty easy to do fast, but it will work on any tree.

    Many different trade offs are relevant for this problem, and the type of tree matters. The problem tends is much easier if you have pointers to parent nodes, and not just to children (Mirko's code uses this)

    See also: http://en.wikipedia.org/wiki/Lowest_common_ancestor

提交回复
热议问题