⼆叉树的层平均值
解法:队列
前题链接:
力扣102.⼆叉树的层序遍历 --python:https://blog.csdn.net/weixin_45047081/article/details/115797910?spm=1001.2014.3001.5501
力扣107.⼆叉树的层次遍历II --python:https://blog.csdn.net/weixin_45047081/article/details/115798522?spm=1001.2014.3001.5501
力扣199.⼆叉树的右视图 --python:https://blog.csdn.net/weixin_45047081/article/details/115798704?spm=1001.2014.3001.5501
还是熟悉的层序遍历,还是熟悉配方
还是和之前一样,获取每一层的节点,这题需要求平均值,因此,刚好可以利用我们的临时列表,求得平均值后再添加进返回值列表内
代码如下:
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:
return []
stack=[root]
rtn=[]
while stack:
size=len(stack)
faker=[]
for _ in range(size):
now=stack.pop(0)
faker.append(now.val)
if now.left:
stack.append(now.left)
if now.right:
stack.append(now.right)
rtn.append(mean(faker))
return rtn