103. Binary Tree Zigzag Level Order Traversal
3
/ \
9 20
/ \
15 7[
[3],
[20,9],
[15,7]
]vector<vector<int>> zigzagLevelOrder(TreeNode* root) { // time: O(n); space: O(n)
vector<vector<int> > res;
if (!root) return res;
queue<TreeNode*> q({root});
vector<int> cur;
bool toRight = true;
while (!q.empty()) {
cur.clear();
for (int i = q.size() - 1; i >= 0; --i) {
TreeNode* t = q.front(); q.pop();
cur.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
if (!toRight) reverse(cur.begin(), cur.end());
toRight = !toRight;
res.push_back(cur);
}
return res;
}Last updated