日野弥生:勉強しよう
LeetCode 572 - 二叉树的层平均值
发表于2025年03月11日
递归解题,求层次均值,则层次遍历一定是优先选择。遍历层级的同时,记录具体是哪一层、以及把同层的个数统计,方便求得平均值。
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
result = []
queue = deque()
if not root:
return result
queue.append([root, 0])
currDepth = 0
currSum = 0
currDepthCount = 0
while queue:
item = queue.popleft()
if item[1] > currDepth:
result.append(currSum / currDepthCount)
currDepth += 1
currSum = item[0].val
currDepthCount = 1
else:
currSum += item[0].val
currDepthCount += 1
if item[0].left:
queue.append([item[0].left, item[1] + 1])
if item[0].right:
queue.append([item[0].right, item[1] + 1])
result.append(currSum / currDepthCount)
return result