637. Average of Levels in Binary Tree

mac2024-08-07  56

文章目录

题目描述Example 1:Note: 题目思路代码

题目描述

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:

The range of node’s value is in the range of 32-bit signed integer.

题目思路

这道题和429. N-ary Tree Level Order Traversal那道题很像,也是广度优先遍历,只不过那道题返回一个列表,这道题返回val的平均值。

代码

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: result = [] cur = [root] nex = [] while cur: sum_ = 0 for node in cur: sum_ += node.val if node.left: nex.append(node.left) if node.right: nex.append(node.right) result.append(sum_ / len(cur)) cur = nex nex = [] return result
最新回复(0)