问题描述
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.
思路
- 建一个全局变量
count
,存当前最大值,并且不受到recursive的影响 - 在大方法里,传root,返回
count
- 用一个recursive方法求树的高度,如果
node
为None
,返回0;每传进一个node
, 先拿到左右两边的subtree分别的高left
和right
,count = max(count, left + right)
;返回max(left, right)+1
class Solution:
count = 0
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.getH(root)
return self.count
def getH(self, node):
if not node:
return 0
left = self.getH(node.left)
right = self.getH(node.right)
self.count = max(self.count, left + right) #update count
return max(left, right)+1