|
| 1 | +# LeetCode 第 102 号问题:二叉树的层序遍历 |
| 2 | + |
| 3 | +> 本文首发于公众号「五分钟学算法」,是[图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>)系列文章之一。 |
| 4 | +> |
| 5 | +> 个人网站:[https://www.cxyxiaowu.com](https://www.cxyxiaowu.com) |
| 6 | +
|
| 7 | +题目来源于 LeetCode 上第 102 号问题:二叉树的层序遍历。题目难度为 Medium,目前通过率为 55.8% 。 |
| 8 | + |
| 9 | +### 题目描述 |
| 10 | + |
| 11 | +给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 |
| 12 | + |
| 13 | +例如: |
| 14 | +给定二叉树: `[3,9,20,null,null,15,7]`, |
| 15 | + |
| 16 | +``` |
| 17 | + 3 |
| 18 | + / \ |
| 19 | + 9 20 |
| 20 | + / \ |
| 21 | + 15 7 |
| 22 | +``` |
| 23 | + |
| 24 | +返回其层次遍历结果: |
| 25 | + |
| 26 | +``` |
| 27 | +[ |
| 28 | + [3], |
| 29 | + [9,20], |
| 30 | + [15,7] |
| 31 | +] |
| 32 | +``` |
| 33 | + |
| 34 | +### 题目解析 |
| 35 | + |
| 36 | +该问题需要用到**队列** |
| 37 | + |
| 38 | +- 建立一个queue |
| 39 | +- 先把根节点放进去,这时候找根节点的左右两个子节点 |
| 40 | +- 去掉根节点,此时queue里的元素就是下一层的所有节点 |
| 41 | +- 用for循环遍历,将结果存到一个一维向量里 |
| 42 | +- 遍历完之后再把这个一维向量存到二维向量里 |
| 43 | +- 以此类推,可以完成层序遍历 |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +### 动画描述 |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | +### 代码实现 |
| 56 | + |
| 57 | +``` |
| 58 | +/// BFS |
| 59 | +/// Time Complexity: O(n), where n is the number of nodes in the tree |
| 60 | +/// Space Complexity: O(n) |
| 61 | +class Solution { |
| 62 | +public: |
| 63 | + vector<vector<int>> levelOrder(TreeNode* root) { |
| 64 | +
|
| 65 | + vector<vector<int>> res; |
| 66 | + if(root == NULL) |
| 67 | + return res; |
| 68 | +
|
| 69 | + queue<pair<TreeNode*,int>> q; |
| 70 | + q.push(make_pair(root, 0)); |
| 71 | +
|
| 72 | + while(!q.empty()){ |
| 73 | +
|
| 74 | + TreeNode* node = q.front().first; |
| 75 | + int level = q.front().second; |
| 76 | + q.pop(); |
| 77 | +
|
| 78 | + if(level == res.size()) |
| 79 | + res.push_back(vector<int>()); |
| 80 | + assert( level < res.size() ); |
| 81 | +
|
| 82 | + res[level].push_back(node->val); |
| 83 | + if(node->left) |
| 84 | + q.push(make_pair(node->left, level + 1 )); |
| 85 | + if(node->right) |
| 86 | + q.push(make_pair(node->right, level + 1 )); |
| 87 | + } |
| 88 | +
|
| 89 | + return res; |
| 90 | + } |
| 91 | +}; |
| 92 | +
|
| 93 | +``` |
| 94 | + |
| 95 | + |
| 96 | + |
| 97 | + |
| 98 | + |
| 99 | + |
0 commit comments