1. 题目来源
同类题:
题单:
- 链表、二叉树与一般树(前后指针/快慢指针/DFS/BFS/直径/LCA)
- §2.13 BFS
2. 题目解析
层序:默写即可
友情链接:
[M二叉树] lc102. 二叉树的层序遍历(队列+bfs)
[M二叉树] lc145. 二叉树的后序遍历(栈+dfs)
[M二叉树] lc94. 二叉树的中序遍历(栈+dfs)
[M二叉树] lc144. 二叉树的前序遍历(栈+dfs)
迭代代码:
/**
* 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) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if (!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
bool flag = false;
while (q.size()) {
vector<int> t;
int n = q.size();
for (int i = 0; i < n; i ++ ) {
auto r = q.front(); q.pop();
t.push_back(r->val);
if (r->left) q.push(r->left);
if (r->right) q.push(r->right);
}
if (flag) reverse(t.begin(), t.end());
res.push_back(t);
flag = !flag;
}
return res;
}
};