103. Binary Tree Zigzag Level Order Traversal

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]
]
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

Was this helpful?