543. Diameter of Binary Tree

在整个树里寻找某个最大数据,还是类似Q968和Q124的思路,dfs遍历同时传递局部解。

968. Binary Tree Cameras124. Binary Tree Maximum Path Sum
  • 叶子节点是初始状态,左右子树的最大diameter都是0

  • 穿过每个节点的可能最大解,都是左子树diameter+1再加上右子树diameter+1,画图很好理解。

  • 所以不停向上传递左右子树分别的diameter即可。

没事儿做还是别拿C++传递数组了,要么用指针搞自己,要么pair累死。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if not root: return 0
        self.diameter = 0
        self.postorder(root)
        return self.diameter
    
    def postorder(self, root):
        if not root.left and not root.right: return (0, 0)
        l = self.postorder(root.left) if root.left else (-1, -1) 
        leftPath = max(l) + 1
        r = self.postorder(root.right) if root.right else (-1, -1)
        rightPath = max(r) + 1
        self.diameter = max(self.diameter, leftPath+rightPath)
        return (leftPath, rightPath)

Last updated

Was this helpful?