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

后端 未结 7 2003
渐次进展
渐次进展 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:39

    As everybody here seems to know, if you keep a note of the distance each node is from the root, then once you have found the lowest common ancestor of the two nodes you can work out the distance they are from each other in constant time.

    If you do one time work only linear in the size of the tree it turns out that you can then find the lowest common ancestor of any two nodes in constant time (no matter how deep the tree is). See http://en.wikipedia.org/wiki/Lowest_common_ancestor

    The Baruch Schieber and Uzi Vishkin algorithm for lowest common ancestor is entirely practical to use and to program.

    0 讨论(0)
提交回复
热议问题