寻找快速算法找到在二叉树的两个节点之间的距离 [英] Looking for fast algorithm to find distance between two nodes in binary tree

查看:225
本文介绍了寻找快速算法找到在二叉树的两个节点之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何找到一个二叉树两个节点之间的距离?等价的,有什么算法那里找到两个节点的最近的共同祖先(最低的共同祖先)?

解决方案
  1. 计算祖先的列表中为每个节点
  2. 找到共同preFIX
  3. 从普通preFIX的最后一个元素是最低的共同祖先
  4. 从两个祖先列表中删除共同preFIX
  5. 的距离的剩余列表长度的总和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?

解决方案

  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

这篇关于寻找快速算法找到在二叉树的两个节点之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆