1 class Solution: 2 def __init__(self): 3 self.maxAvg = 0 4 5 def preOrder(self,node): 6 if node == None: 7 return 0,0 8 leftcount,leftsum = self.preOrder(node.left) 9 rightcount,rightsum = self.preOrder(node.right) 10 totalcount = leftcount + rightcount + 1 11 totalsum = leftsum + rightsum + node.val 12 avg = totalsum / totalcount 13 self.maxAvg = max(self.maxAvg,avg) 14 return totalcount,totalsum 15 16 def maximumAverageSubtree(self, root: TreeNode) -> float: 17 self.preOrder(root) 18 return self.maxAvg
后序遍历,遍历的同时计算节点的数量、节点的和,并求平均值。