方法一:
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.ans = 1
def depth(node):
if not node: return 0
L = depth(node.left)
R = depth(node.right)
self.ans = max(self.ans, L+R+1)
return max(L, R)+1
depth(root)
return self.ans-1
方法二:
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.max = 0
self.depth(root)
return self.max
def depth(self.root):
if not root: return 0
l = self.depth(root.left)
r = self.depth(root.right)
self.max = max(self.max, l+r)
return max(l, r) + 1