2019-05-02 15:59:01 +08:00
|
|
|
|
# LeetCode 第 102 号问题:二叉树的层序遍历
|
|
|
|
|
|
|
|
|
|
> 本文首发于公众号「五分钟学算法」,是[图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>)系列文章之一。
|
|
|
|
|
>
|
|
|
|
|
> 个人网站:[https://www.cxyxiaowu.com](https://www.cxyxiaowu.com)
|
|
|
|
|
|
|
|
|
|
题目来源于 LeetCode 上第 102 号问题:二叉树的层序遍历。题目难度为 Medium,目前通过率为 55.8% 。
|
|
|
|
|
|
|
|
|
|
### 题目描述
|
|
|
|
|
|
|
|
|
|
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
|
|
|
|
|
|
|
|
|
|
例如:
|
|
|
|
|
给定二叉树: `[3,9,20,null,null,15,7]`,
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
3
|
|
|
|
|
/ \
|
|
|
|
|
9 20
|
|
|
|
|
/ \
|
|
|
|
|
15 7
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
返回其层次遍历结果:
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
[
|
|
|
|
|
[3],
|
|
|
|
|
[9,20],
|
|
|
|
|
[15,7]
|
|
|
|
|
]
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
### 题目解析
|
|
|
|
|
|
|
|
|
|
该问题需要用到**队列**
|
|
|
|
|
|
|
|
|
|
- 建立一个queue
|
|
|
|
|
- 先把根节点放进去,这时候找根节点的左右两个子节点
|
|
|
|
|
- 去掉根节点,此时queue里的元素就是下一层的所有节点
|
|
|
|
|
- 用for循环遍历,将结果存到一个一维向量里
|
|
|
|
|
- 遍历完之后再把这个一维向量存到二维向量里
|
|
|
|
|
- 以此类推,可以完成层序遍历
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
### 动画描述
|
|
|
|
|
|
2019-11-14 11:00:28 +08:00
|
|
|
|
![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/2elr5.gif)
|
2019-05-02 15:59:01 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
### 代码实现
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
/// BFS
|
|
|
|
|
/// Time Complexity: O(n), where n is the number of nodes in the tree
|
|
|
|
|
/// Space Complexity: O(n)
|
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
vector<vector<int>> levelOrder(TreeNode* root) {
|
|
|
|
|
|
|
|
|
|
vector<vector<int>> res;
|
|
|
|
|
if(root == NULL)
|
|
|
|
|
return res;
|
|
|
|
|
|
|
|
|
|
queue<pair<TreeNode*,int>> q;
|
|
|
|
|
q.push(make_pair(root, 0));
|
|
|
|
|
|
|
|
|
|
while(!q.empty()){
|
|
|
|
|
|
|
|
|
|
TreeNode* node = q.front().first;
|
|
|
|
|
int level = q.front().second;
|
|
|
|
|
q.pop();
|
|
|
|
|
|
|
|
|
|
if(level == res.size())
|
|
|
|
|
res.push_back(vector<int>());
|
|
|
|
|
assert( level < res.size() );
|
|
|
|
|
|
|
|
|
|
res[level].push_back(node->val);
|
|
|
|
|
if(node->left)
|
|
|
|
|
q.push(make_pair(node->left, level + 1 ));
|
|
|
|
|
if(node->right)
|
|
|
|
|
q.push(make_pair(node->right, level + 1 ));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-14 11:00:28 +08:00
|
|
|
|
![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/96yrg.png)
|