VIRTUALS

the virtual labs for the virtuals

0%

LeetCode 102. 二叉树的层序遍历

摘要:
二叉树基础。

题目

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

示例:
二叉树:$[3,9,20,null,null,15,7]$

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回其层序遍历结果:

1
2
3
4
5
[
[3],
[9,20],
[15,7]
]

二叉树定义:

1
2
3
4
5
6
7
8
9
10
11
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
1
2
3
4
5
6
7
8
9
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

BFS

直接队列BFS。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
* 2021-6-26 09:55:29
* author: etoa
*/
static const auto shutdown = [](){
cin.tie(nullptr)->sync_with_stdio(false);
return nullptr;
}();

class Solution {
public:
static constexpr int N = 1010;
TreeNode* q[N];
int hh = 0, tt = -1;

vector<vector<int>> res;
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return res;
q[++tt] = root;
for (; tt >= hh;) {
vector<int> level;
for (int len = tt - hh + 1; len; len--, hh++) {
TreeNode* node = q[hh];
level.emplace_back(node->val);
if (node->left)
q[++tt] = node->left;
if (node->right)
q[++tt] = node->right;
}
res.emplace_back(level);
}
return res;
}
};

DFS

可以在dfs函数中维护一个 level 变量,递归遍历这颗二叉树,将每个节点值放入到对应层的数组中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
* 2021-6-26 10:11:16
* author: etoa
*/
static const auto shutdown = [](){
cin.tie(nullptr)->sync_with_stdio(false);
return nullptr;
}();

class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> levelOrder(TreeNode* root) {
dfs(root, 0);
return res;
}

void dfs(TreeNode* node, int level) {
if (!node) return;
if (res.size() <= level) {
vector<int> lvl;
res.push_back(lvl);
}
res[level].push_back(node->val);
if (node->left)
dfs(node->left, level + 1);
if (node->right)
dfs(node->right, level + 1);
}
};