注意
直径未必需要经过root
因此要遍历每一个节点 以它作为输入
以一个点为输入root的最长直径,即1 + 左子树最大边数 + 1 +右子树最大边数
计算完一个节点下有多少条边以后,计入字典
最后返回的结果是一个全局最长直径
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.maxlength = None
self.dict_log = {}
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if root == None:
return 0
depth_left = 1 + self.find_depth(root.left) if root.left != None else 0
depth_right = 1 + self.find_depth(root.right) if root.right != None else 0
return max(depth_left + depth_right,self.diameterOfBinaryTree(root.left),self.diameterOfBinaryTree(root.right))# - 2
def find_depth(self,root):
if root == None:
return 0
if root in self.dict_log:
return self.dict_log[root]
depth = 0
if root.left == None and root.right == None:
self.dict_log[root] = depth
return depth
res = max(self.find_depth(root.left),self.find_depth(root.right)) + 1
self.dict_log[root] = res
return res