Tree层遍历
Tree层遍历
- 102 Binary Tree Level Order Traversal
- 107 Binary Tree Level Order Traversal II
- 1302. Deepest Leaves Sum
- 637 Average of Levels in Binary Tree
102 Binary Tree Level Order Traversal
题目
Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
例子
1 | Input: root = [3,9,20,null,null,15,7] |
思路
此题属于比较常见的BFS遍历,即通过一个队列将同一层的节点遍历一遍,然后入列下一层的节点,循环。不过需要注意一些 None 的conner case处理。
代码
1 | class Solution: |
107 Binary Tree Level Order Traversal II
题目
Given the root of a binary tree, return the bottom-up level order traversal of its nodes’ values. (i.e., from left to right, level by level from leaf to root).
思路
此题是上一题的倒叙模式。最直接的方法是采用上题的解法,然后reverse结果。或者我们也可以直接采用queue进行,不过需要多一个状态记录层数。
代码
1 | # dfs recursively |
637 Average of Levels in Binary Tree
题目
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.
例子
1 | Input: root = [3,9,20,null,15,7] |
思路
简单说这题就是求每一层的平均数。同样的思路,用一个queue包括所有的该层节点。
代码
1 | class Solution: |
1302. Deepest Leaves Sum
题目
Given the root of a binary tree, return the sum of values of its deepest leaves.
例子
1 | Example 1: |
思路
此题仍然是安层遍历,只不过我们只关心最后一层的数据。因此我们写一个循环,每一次搜集所有该层的节点,直到没有节点为止,此时queue剩下的元素就是我们需要的。
代码
1 | class Solution: |