Looking for fast algorithm to find distance between two nodes in binary tree

后端 未结 7 2034
渐次进展
渐次进展 2020-12-31 05:03

How do I find the distance between two nodes in a binary tree? Equivalently, what algorithms are there for finding the most recent common ancestor (lowest common ancestor)

7条回答
  •  耶瑟儿~
    2020-12-31 05:32

    Make two sets consisting of the ancestors of each: while the union of the sets is empty, add the next ancestor of each node to the appropriate list. Once there is a common node, that's the common ancestor.

提交回复
热议问题