思路
其实就是求每个节点左右子树高度和的最大值
可以结合树的深度的递归求法,在递归的同时记录每个节点高度和的最大值
class Solution(object):
def __init__(self):
self.depth_max = 0
def diameterOfBinaryTree(self, root):
if not root:
return 0
def depth(root):
if not root:
return 0
# if not root.left or not root.right:
# return 1
lmax = depth(root.left)
rmax = depth(root.right)
self.depth_max = max(self.depth_max, lmax + rmax)
return max(lmax, rmax) + 1
depth(root)
return self.depth_max
思路二
三种可能
- 不包含节点x,则结果为左子树最大直径
- 不包含节点x,则结果为右子树最大直径
- 包含节点x,则结果为左子树深度+右子树深度+1
返回三种情况中的最大值
class Solution(object):
def diameterOfBinaryTree(self, root):
if not root:
return 0
l = self.diameterOfBinaryTree(root.left) #左子树最大直径
r = self.diameterOfBinaryTree(root.right) #右子树最大直径
lh = self.height(root.left) #左子树深度
rh = self.height(root.right) #右子树深度
return max(l,r,lh+rh)
#计算树的深度
def height(self,root):
if not root:
return 0
if not root.left and not root.right:
return 1
return max(self.height(root.left), self.height(root.right)) + 1