Leetcode 543. 二叉树的直径-----python
2019-06-12 11:31
1411 查看
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例 :
给定二叉树
解题思路:
注意看[4,2,1,3]或[5,2,1,3],是左右两棵子树路径加起来的。
- 二叉树的直径:二叉树中从一个结点到另一个节点最长的路径,叫做二叉树的直径
- 采用分治和递归的思想:根节点为root的二叉树的直径 =
max(root-left的直径,root->right的直径,root->left的最大深度+root->right的最大深度+1)
python代码实现:
class Solution(object): def __init__(self): self.res = 0 def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ def getMaxDepth(root): if root == None: return 0 left = getMaxDepth(root.left) right = getMaxDepth(root.right) self.res = max(self.res, left+right) return max(left, right) + 1 if root == None: return 0 getMaxDepth(root) return self.res
相关文章推荐
- leetcode-腾讯精选练习(50 题)python #104 二叉树的最大深度
- LeetCode 114.二叉树展开为链表(Python实现)
- leetcode解题之543. Diameter of Binary Tree Java版 (二叉树的最大直径)
- LeetCode700 二叉树中的搜索 python3
- LeetCode 331. Verify Preorder Serialization of a Binary Treet 二叉树前序遍历验证 Python Solution
- Leetcode 104 python 二叉树的最大深度
- 利用python 完成 leetcode 199 二叉树的右视图
- leetcode | 按层访问一棵二叉树 | Python
- 利用python 完成leetcode 114 二叉树展开为链表
- LeetCode--Invert Binary Tree (反转二叉树)Python
- LeetCode 543. Diameter of Binary Tree (二叉树的直径)
- [和小菜鸡一起刷题(python)] LeetCode 199. 二叉树的右视图. (Binary Tree Right Side View)
- leetcode-二叉树右视图(python)
- LeetCode--Merge Two Binary Trees(合并两个二叉树)Python
- Leetcode 94 python 二叉树的中序遍历
- Leetcode 145 python 二叉树的后序遍历
- Leetcode107. 二叉树的层次遍历 II(python3)
- LeetCode--Maximum Depth of Binary Tree (检索二叉树的最大深度)Python
- [LeetCode]543. Diameter of Binary Tree(计算二叉树的直径的长度)
- Leetcode 144 python 二叉树的前序遍历