二叉树最大距离(直径)
方法一 计算每个节点的左子树和右子树的高度和,加上根本身(边数为2),取最大值
二叉树的最大距离,一定是经过根或者某个子树的根的路径,其两个端点必然是叶子节点或者根节点。计算二叉树的高度,并且比较经过该节点的最大距离,取
最大者。其中,getTreeDistance的起点是-1,其值为二叉树的高度减1,即高度路径上的点之间的边的条数,即距离。getTreeDistance引入了新的概念描述,
getTreeHeight是求树的高度,但是其计算时候要减去1.经过一个根节点的最大距离,就是其左子树最大高度距离(不是最大距离),加上其右子树最大高度距离,加上
左右到根节点的距离,即2,然后与一个外部变量比较,因此使用了两个函数。
实现代码如下:
function Node(val){ this.val = val; this.left = null; this.right = null; }
function getMaxDistance(){ var max_d = 0; getTreeHeight(root);//或者getTreeDistance(root); return max_d; }
function getTreeDistance(root){ if(!root){ return -1; } var lh = getTreeDistance(root.left), rh = getTreeDistance(root.right); var distance = lh + rh + 2; max_d = Math.max(distance,max_d); return Math.max(lh,rh) + 1; }
function getTreeHeight(root){ if(!root){ return 0; } var lh = getTreeHeight(root.left), rh = getTreeHeight(root.right); var distance = (lh -1) + (rh - 1) + 2; max_d = Math.max(distance,max_d); return Math.max(lh,rh) + 1; }
方法二 按照节点是否跨根,分为左子树最大距离,右子树最大距离,左右子树最大深度加到根节点的距离,即2,取最大者
同样区分高度距离和高度,起点不同,高度距离为-1,高度为0,用对象距离结果,然后返回。
function getMaxDistance(root){ if(!root){ return { maxDist:-1, maxDistance:0 } } var lRes = getMaxDistance(root.left), rRes = getMaxDistance(root.right); var result = { maxDist:Math.max(lRes.maxDist,rRes.maxDist) + 1, maxDistance:Math.max(lRes.maxDistance,rRes.maxDistance,lRes.maxDist + rRes.maxDist + 2) } return result; } function getMaxDistance(root){ if(!root){ return { maxDepth:0, maxDistance:0 } } var lRes = getMaxDistance(root.left), rRes = getMaxDistance(root.right); var result = { maxDepth:Math.max(lRes.maxDepth,rRes.maxDepth) + 1, maxDistance:Math.max(lRes.maxDistance,rRes.maxDistance,(lRes.maxDepth-1) + (rRes.maxDepth-1) + 2) } return result; }
出处: http://blog.csdn.net/flyinghearts/article/details/5605995
http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-05-17 sublime text快捷键
2016-05-17 Mac按键