Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
Solution
/**
* 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>> values;
if (root == nullptr) return values;
stack<TreeNode*> cur, next;
cur.push(root);
auto *curptr = &cur, *nextptr = &next;
bool flag = false;
while (!curptr->empty()) {
flag = !flag;
values.emplace_back(vector<int>());
values.back().reserve(curptr->size());
if (flag) {
while (!curptr->empty()) {
values.back().emplace_back(curptr->top()->val);
if (curptr->top()->left) nextptr->push(curptr->top()->left);
if (curptr->top()->right) nextptr->push(curptr->top()->right);
curptr->pop();
}
} else {
while (!curptr->empty()) {
values.back().emplace_back(curptr->top()->val);
if (curptr->top()->right) nextptr->push(curptr->top()->right);
if (curptr->top()->left) nextptr->push(curptr->top()->left);
curptr->pop();
}
}
auto *temp = curptr;
curptr = nextptr;
nextptr = temp;
}
return values;
}
};