作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/submissions/detail/136579829/

题目描述

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

Example 1:

  1. Input:
  2. 3
  3. / \
  4. 9 20
  5. / \
  6. 15 7
  7. Output: [3, 14.5, 11]
  8. Explanation:
  9. 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:

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

题目大意

求二叉树每层的所有节点的平均值

解题方法

方法一:DFS

这个题需要保存每层的节点的和以及每层的节点数。采用DFS的方式,把每个节点进行遍历,把这个节点加到对应层中去。每层使用两个数字,第一个数字保存所有节点的和,第二个数字保存有多少个节点。

注意一个小问题,节点为空的时候要return,否则下面node为None,出现错误。

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def averageOfLevels(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: List[float]
  12. """
  13. info = [] # the first element is sum of the level,the second element is nodes in this level
  14. def dfs(node, depth=0):
  15. if not node:
  16. return
  17. if len(info) <= depth:
  18. info.append([0, 0])
  19. info[depth][0] += node.val
  20. info[depth][1] += 1
  21. # print(info)
  22. dfs(node.left, depth + 1)
  23. dfs(node.right, depth + 1)
  24. dfs(root)
  25. return [s / float(c) for s,c in info]

二刷。直接使用数组保存每层所有节点的值,最后需要做个求平均数的处理。

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def averageOfLevels(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: List[float]
  12. """
  13. res = []
  14. self.getLevel(root, 0, res)
  15. return [sum(line) / float(len(line)) for line in res]
  16. def getLevel(self, root, level, res):
  17. if not root:
  18. return
  19. if level >= len(res):
  20. res.append([])
  21. res[level].append(root.val)
  22. self.getLevel(root.left, level + 1, res)
  23. self.getLevel(root.right, level + 1, res)

方法二:BFS

其实层次遍历使用BFS比使用DFS更加简单高效。因为每层遍历结束之后,已经知道了这一行的所有数字,所以可以直接求平均数,然后放入到结果中去,而不用最后才求平均数了。

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def averageOfLevels(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: List[float]
  12. """
  13. que = collections.deque()
  14. res = []
  15. que.append(root)
  16. while que:
  17. size = len(que)
  18. row = []
  19. for _ in range(size):
  20. node = que.popleft()
  21. if not node:
  22. continue
  23. row.append(node.val)
  24. que.append(node.left)
  25. que.append(node.right)
  26. if row:
  27. res.append(sum(row) / float(len(row)))
  28. return res

日期

2018 年 1 月 17 日
2018 年 11 月 9 日 —— 睡眠可以

【LeetCode】637. Average of Levels in Binary Tree 解题报告(Python)的更多相关文章

  1. LeetCode 637 Average of Levels in Binary Tree 解题报告

    题目要求 Given a non-empty binary tree, return the average value of the nodes on each level in the form ...

  2. [LeetCode] 637. Average of Levels in Binary Tree 二叉树的层平均值

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

  3. LeetCode 637. Average of Levels in Binary Tree二叉树的层平均值 (C++)

    题目: Given a non-empty binary tree, return the average value of the nodes on each level in the form o ...

  4. LeetCode - 637. Average of Levels in Binary Tree

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

  5. LeetCode 637. Average of Levels in Binary Tree(层序遍历)

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

  6. 637. Average of Levels in Binary Tree - LeetCode

    Question 637. Average of Levels in Binary Tree Solution 思路:定义一个map,层数作为key,value保存每层的元素个数和所有元素的和,遍历这 ...

  7. 【Leetcode_easy】637. Average of Levels in Binary Tree

    problem 637. Average of Levels in Binary Tree 参考 1. Leetcode_easy_637. Average of Levels in Binary T ...

  8. 【LeetCode】662. Maximum Width of Binary Tree 解题报告(Python)

    [LeetCode]662. Maximum Width of Binary Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.co ...

  9. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

随机推荐

  1. Linux—查看内核版本、系统版本、系统位数

    一.查看内核版本命令: 1) [root@q1test01 ~]# cat /proc/version   Linux version 2.6.9-22.ELsmp (bhcompile@crowe. ...

  2. 48-Merge Sorted Array

    $88. Merge Sorted Array My Submissions QuestionEditorial Solution Total Accepted: 98885 Total Submis ...

  3. gcc 引用math 库 编译的问题 解决方法

    1.gcc app.c -lm 其中lm表示的是连接 m forlibm.so / libm.a表示你想要的库 abc for libabc.so / libabc.a 其中.a表示的是静态链接库 . ...

  4. Python中的随机采样和概率分布(二)

    在上一篇博文<Python中的随机采样和概率分布(一)>(链接:https://www.cnblogs.com/orion-orion/p/15647408.html)中,我们介绍了Pyt ...

  5. 巩固javaweb的第二十五天

    常用的验证 1. 非空验证 // 验证是否是空 function isNull(str) { if(str.length==0) return true; else return false; } 2 ...

  6. 【Reverse】每日必逆0x03

    BUU-刮开有奖 附件:https://files.buuoj.cn/files/abe6e2152471e1e1cbd9e5c0cae95d29/8f80610b-8701-4c7f-ad60-63 ...

  7. Docker学习(六)——Dockerfile文件详解

    Docker学习(六)--Dockerfile文件详解 一.环境介绍 1.Dockerfile中所用的所有文件一定要和Dockerfile文件在同一级父目录下,可以为Dockerfile父目录的子目录 ...

  8. Docker 生产环境之配置容器 - 自动启动容器

    原文地址 Docker 提供了重启策略,以控制容器在退出时是否自动启动,或在 Docker 重新启动时自动启动.重启策略可确保链接的容器以正确的顺序启动.Docker 建议使用重启策略,并避免使用流程 ...

  9. Default Constructors

    A constructor without any arguments or with default value for every argument, is said to be default ...

  10. ES6(模板字符串,三点运算符,Symbol,iterator接口)

    模板字符串 作用:简化字符串的拼接 模板字符串必须用``包含 变化的部分使用${xxx}包含 对象的简写方式 同名的属性可以省略不写 可以省略函数的function 箭头函数 箭头函数的特点 箭头函数 ...