leetcode 找到树中距离最大的两个结点,Python实现
来源:互联网 发布:成都租房 知乎 编辑:程序博客网 时间:2024/05/22 01:30
题目:
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1 / \ 2 3 / \ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
(Note: 两个结点之间的距离=两个结点之间 “边”(即连线)的数目)思路:
1. 计算以当前点为根结点时,树的最大深度;
2. 选出当前结点,以及其左、右子结点距离最大者;
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 max_dia_left = self.diameterOfBinaryTree(root.left) max_dia_right = self.diameterOfBinaryTree(root.right) max_dia = max(self.get_depth(root.left)+self.get_depth(root.right),max_dia_left,max_dia_right) # max: 1.当前结点最大距离;2.左、右子结点的最大距离 return max_dia def get_depth(self,root): #计算以当前结点为根时,树的最大深度; if not root: return 0 else: return max(1+self.get_depth(root.left),1+self.get_depth(root.right))
阅读全文
0 0
- leetcode 找到树中距离最大的两个结点,Python实现
- 求一个二叉树中两个结点的最大距离
- 通过邻接矩阵找到两个节点的最近公共祖先结点
- (整理)Java实现链表--找到两个链表的第一个公共结点(网易笔试题2016)
- 二叉树的最大结点
- 求二叉树中距离最远的两个叶子节点的距离
- python找到两个有序列表的中位数
- 利用栈结构实现二叉树的非递归遍历,求二叉树深度、叶子节点数、两个结点的最近公共祖先及二叉树结点的最大距离
- 利用栈结构实现二叉树的非递归遍历,求二叉树深度、叶子节点数、两个结点的最近公共祖先及二叉树结点的最大距离
- 利用栈结构实现二叉树的非递归遍历,求二叉树深度、叶子节点数、两个结点的最近公共祖先及二叉树结点的最大距离
- 第19题 在二叉查找树中找到两个结点的最低公共祖先 Lowest Common Ancestor
- 019写程序在一棵二叉树中找到两个结点的最近共同祖先(keep it up)
- 在含有父结点指针的二叉树中找到一个结点的后继结点
- 在一个数组中找到最大的两个数
- 找到两个不相容子数组的最大和
- 求二叉树的所有结点之和,Python实现
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- 二叉树两个结点的最低共同父结点
- Android学习十 多媒体
- Struts2拦截器的实现
- Linux内存管理详细解析
- LeetCode——Hamming Distance
- python装饰器
- leetcode 找到树中距离最大的两个结点,Python实现
- JS检测设备类型
- 分块查找
- 中国大学慕课C语言第五讲作业
- vc++ ios::in ios::out 含义
- ptmalloc
- JAVA反射机制
- springboot笔记
- NYOJ-325Zb的生日