持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天,点击查看活动详情
102. 二叉树的层序遍历
思路:
用一个队列维护每个节点,然后节点的孩子入手,将其孩子放入队列中
代码:
class Solution {
public:
vector<vector<int>> result;
queue<TreeNode*> res;
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr) return result;
res.push(root);
while (!res.empty()) {
int s = res.size();
vector<int> ret;
for (int i = 0; i < s; i++) {
auto font = res.front();
ret.push_back(font->val);
res.pop();
if (font->left) res.push(font->left);
if (font->right) res.push(font->right);
}
result.push_back(ret);
}return result;
}
};
107. 二叉树的层序遍历 II
思路:
直接将其进行反转即可
代码:
class Solution {
public:
vector<vector<int>> result;
queue<TreeNode*> res;
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if (root == nullptr) return result;
res.push(root);
while (!res.empty()) {
int s = res.size();
vector<int> ret;
for (int i = 0; i < s; i++) {
auto font = res.front();
ret.push_back(font->val);
res.pop();
if (font->left) res.push(font->left);
if (font->right) res.push(font->right);
}
result.push_back(ret);
}
reverse(result.begin(), result.end());
return result;
}
};
103. 二叉树的锯齿形层序遍历
思路:
用一个数d(0,1)来表示,使其隔一次反转一次
代码:
class Solution {
public:
vector<vector<int>> result;
queue<TreeNode*> res;
int d = 1;
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if (root == nullptr) return result;
res.push(root);
while (!res.empty()) {
int s = res.size();
vector<int> ret;
for (int i = 0; i < s; i++) {
auto font = res.front();
ret.push_back(font->val);
res.pop();
if (font->left) res.push(font->left);
if (font->right) res.push(font->right);
}
if (d == 0) {
reverse(ret.begin(), ret.end());
d = 1;
}
else d = 0;
result.push_back(ret);
}return result;
}
};
429. N 叉树的层序遍历
思路;
与二叉树的层序遍历一样,只不过这次是不只左右孩子
代码:
class Solution {
public:
vector<vector<int>> result;
queue<Node*> res;
vector<vector<int>> levelOrder(Node* root) {
if (!root) return result;
res.push(root);
while (!res.empty()) {
int z = res.size();
vector<int> ret;
for (int i = 0; i < z; i++) {
auto m = res.front();
ret.push_back(m->val);
res.pop();
for (auto j : m->children) {
res.push(j);
}
}
result.push_back(ret);
}
return result;
}
};