设置后续遍历函数,返回左右子树的节点值的和以及节点数量。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maximumAverageSubtree(self, root: TreeNode) -> float:
self.max = float('-inf')
def afterorder(root):
if not root:return [0, 0]
lv, lc = afterorder(root.left)
rv, rc = afterorder(root.right)
val = (root.val + lv + rv)
amount = lc+rc+1
self.max = max(self.max, val/amount)
return [val, amount]
afterorder(root)
return self.max