寻找快速算法找到在二叉树的两个节点之间的距离 [英] Looking for fast algorithm to find distance between two nodes in binary tree
本文介绍了寻找快速算法找到在二叉树的两个节点之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何找到一个二叉树两个节点之间的距离?等价的,有什么算法那里找到两个节点的最近的共同祖先(最低的共同祖先)?
解决方案
- 计算祖先的列表中为每个节点
- 找到共同preFIX
- 从普通preFIX的最后一个元素是最低的共同祖先
- 从两个祖先列表中删除共同preFIX
- 的距离的剩余列表长度的总和1
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) of two nodes?
解决方案
- calculate the list of ancestors for each node
- find the common prefix
- the last element from the common prefix is the lowest common ancestor
- remove the common prefix from both ancestor lists
- the distance is the sum of lengths of the remaining lists +1
这篇关于寻找快速算法找到在二叉树的两个节点之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文