class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
height = {None:(0,0)}
def getheight(root):
if root in height: return height[root]
l,r = getheight(root.left), getheight(root.right)
res = (1+max(l), 1+max(r))
height[root] = res
return res
getheight(root)
def helper(root):
if not root: return 0
return max([helper(root.left), helper(root.right), sum(height[root])-2])
return helper(root)
543. Diameter of Binary Tree
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 递归的时候最好把递归表达式值保存起来,不要反复递归调用,不然会超时。 这道题我一开始是直接把根结点的左右子树高度相...
- Description Given a binary tree, you need to compute the ...
- Easy跟之前做过的有一道题很像,也是用height() method写,但是并不是返回height, 只是在求h...
- 题目 Given a binary tree, you need to compute the length of...