由于求的是树的边的最长长度,则递归过程由左 -> 右 -> 根 顺序进行,并在递归过程中记录 左子树直径 和 右子树直径的和的最大值
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类
# @return int整型
#
class Solution:
def __init__(self):
self.path = 0
def diameterOfBinaryTree(self , root: TreeNode) -> int:
# write code here
if not root:
return 0
self.subBinaryTree(root)
return self.path
def subBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
l = self.subBinaryTree(root.left)
r = self.subBinaryTree(root.right)
self.path = max(self.path, l + r)
return max(l, r) + 1