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

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

    Finding the common ancestor is almost certainly the easier task. This is a pretty simple one: start from the root of the tree, and descend the tree until you reach a node where you would have to descend to different children to get to the two nodes in question. That node is the common parent (assuming the tree contains both nodes, of course).

提交回复
热议问题