問題描述
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.
思路
- 建一個(gè)全局變量
count,存當(dāng)前最大值,并且不受到recursive的影響 - 在大方法里,傳root,返回
count - 用一個(gè)recursive方法求樹的高度,如果
node為None,返回0;每傳進(jìn)一個(gè)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