二叉树问题---二叉树节点间的最大距离
来源:互联网 发布:f1 2015知乎 编辑:程序博客网 时间:2024/06/05 06:43
问题:
从二叉树节点A出发,可以向上或者向下走,但沿途的节点只能经过一次,当到达节点B时,路径上的节点数叫做A到B的距离。
基本思路:
一个以h为头的树上,最大的距离只可能来自以下三种情况:
- h左子树上的最大距离
- h右子树上的最大距离
- h左子树上离h.left最远的距离+1+h右子树上离h.right最远的距离
三个值中的最大值就是整棵h树中最远的距离
#python3.5#二叉树节点间的最大距离def maxDistance(head): def posOrder(head, record): if head == None: record[0] = 0 return 0 leftMax = posOrder(head.left, record) maxfromLeft = record[0] rightMax = posOrder(head.right, record) maxfromRight = record[0] record[0] = max(maxfromLeft, maxfromRight) + 1 curMax = maxfromLeft + maxfromRight + 1 return max(max(leftMax, rightMax),curMax) if head == None: return 0 record = [None] #如果使用一个变量,则为值传递,record值不会变 return posOrder(head, record)
阅读全文
2 0
- 二叉树问题---二叉树节点间的最大距离
- 二叉树节点间的最大距离
- 二叉树节点间的最大距离问题
- 二叉树节点间的最大距离问题
- 二叉树节点间的最大距离问题
- 最大距离二叉树节点
- 求二叉树节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 求二叉树节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 二叉树中节点的最大距离
- 求二叉树节点的最大距离
- Python中filter与lambda的结合使用
- Atitit 战略之道 attilax著 v4 r88
- Java基础001
- 网易编程题--数字翻转
- 动态规划
- 二叉树问题---二叉树节点间的最大距离
- h5中视频插入标签 video
- unity 协程笔记
- Standby RAC遭遇ORA-1157,1111,1110导致实例crash处理
- [BZOJ2190][SDOI2008]仪仗队(欧拉函数|莫比乌斯反演)
- 2017.8.11 Oracle Linux安装问题补充
- (二)Supporting Different Devices支持不同的设备
- SSH Secure Shell Client使用
- 忍者跑酷