Leetcode 103. Binary Tree Zigzag Level Order Traversal
Given the root of a binary tree, return the zigzag level order traversal of its nodes’ values. (i.e., from left to right, then right to left for the next level and alternate between).
leftToRight) to keep track of the current traversal direction (left-to-right or right-to-left).leftToRight, append this list to the result (reverse the list if needed).leftToRight indicator after processing each level.#include <iostream>
#include <vector>
#include <queue>
#include <deque>
using namespace std;
// 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) {
vector<vector<int>> result;
if (root == nullptr) return result;
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
bool leftToRight = true;
while (!nodeQueue.empty()) {
int size = nodeQueue.size();
deque<int> currentLevel;
for (int i = 0; i < size; ++i) {
TreeNode* currentNode = nodeQueue.front();
nodeQueue.pop();
if (leftToRight) {
currentLevel.push_back(currentNode->val);
} else {
currentLevel.push_front(currentNode->val);
}
if (currentNode->left != nullptr) {
nodeQueue.push(currentNode->left);
}
if (currentNode->right != nullptr) {
nodeQueue.push(currentNode->right);
}
}
result.push_back(vector<int>(currentLevel.begin(), currentLevel.end()));
leftToRight = !leftToRight;
}
return result;
}
};
nodeQueue) is initialized and the root node is pushed into it if the root is not null.size).currentLevel) to store the values of nodes at the current level.leftToRight is true, append the values to the end of the deque; otherwise, append to the front.leftToRight flag.This ensures that each level is properly captured in zigzag manner.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?