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

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

    1. calculate the list of ancestors for each node
    2. find the common prefix
    3. the last element from the common prefix is the lowest common ancestor
    4. remove the common prefix from both ancestor lists
    5. the distance is the sum of lengths of the remaining lists +1

提交回复
热议问题