题目链接
- LeetCode102.二叉树的层序遍历:102. 二叉树的层序遍历 - 力扣(LeetCode)
- LeetCode103.二叉树的锯齿形层序遍历:103. 二叉树的锯齿形层序遍历 - 力扣(LeetCode)
实现思路
- 定义一个队列,每一轮循环,队列都会放入新的一层的节点;
- 在下一次循环中,取出上一层放入的所有新节点(放入数组中),并依次从队列中踢出这些节点,获取到这些节点的左右孩子,再放入队列中。如此,就达到了1中所说的每一轮循环,最终队列放入的都是新遍历的层次的所有节点(从左到右)。
- 锯齿形:用一个遍历来标记奇/偶数层,奇数层时数组顺序存放在结果中,反之,逆序。
代码实现
class Solution {
public:vector<vector<int>> levelOrder(TreeNode* root) {vector<vector<int>> ans;if (root == nullptr) return ans;queue<TreeNode*> q;q.push(root);while (int s = q.size()) {vector<int> res;for (int i = 0; i < s; i++) {TreeNode* top = q.front();res.push_back(top->val);q.pop();if (top->left) q.push(top->left);if (top->right) q.push(top->right);}ans.push_back(res);}return ans;}
};
class Solution {
public:vector<vector<int>> zigzagLevelOrder(TreeNode* root) {vector<vector<int>> res;if (root == nullptr) return res;queue<TreeNode*> q;q.push(root);bool flag = 0;while (int s = q.size()) {vector<int> ans;TreeNode* cur;for (int i = 0; i < s; i++) {cur = q.front();ans.push_back(cur->val);if (cur->left) q.push(cur->left);if (cur->right) q.push(cur->right);q.pop();}if (flag) reverse(ans.begin(), ans.end());res.push_back(ans);flag = !flag;}return res;}
};