103 Binary Tree Zigzag Level Order Traversal
3
/ \
9 20
/ \
15 7[
[3],
[20,9],
[15,7]
] 3
9 20
3 15 7
20 23Last updated
3
/ \
9 20
/ \
15 7[
[3],
[20,9],
[15,7]
] 3
9 20
3 15 7
20 23Last updated
// initialize queue elements
push(3)
push(null)
^
top(3)
push children 9 and 20
^
top(null)
push(null) // which follows after 9 and 20
^
top(9)
push child 3
^
top(20)
push children 15 and 7
^
top(null)
push(null) // which follows after 3 15 and 7.vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> zig_zag_lvl;
vector<int> v_temp;
if (!root) return zig_zag_lvl;
bool insert_back = true;
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
while (!q.empty()) {
TreeNode* cur_top = q.front();
q.pop();
if (cur_top) {
if (insert_back)
v_temp.push_back(cur_top->val);
else
v_temp.insert(v_temp.begin(), cur_top->val);
if (cur_top->left)
q.push(cur_top->left);
if (cur_top->right)
q.push(cur_top->right);
}
else {
if (!q.empty())
q.push(nullptr);
zig_zag_lvl.push_back(v_temp);
v_temp.clear();
insert_back = !insert_back;
}
}
return zig_zag_lvl;
}