Lowest Common Ancestor of a Binary Tree

后端 未结 6 455
栀梦
栀梦 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 01:02

    Constant space answer: (although not necessarily efficient).

    Have a function findItemInPath(int index, int searchId, Node root)

    then iterate from 0 .. depth of tree, finding the 0-th item, 1-th item etc. in both search paths.

    When you find i such that the function returns the same result for both, but not for i+1, then the i-th item in the path is the lowest common ancestor.

提交回复
热议问题