---
# System prepended metadata

title: LC 103. Binary Tree Zigzag Level Order Traversal
tags: [BFS, medium, leedcode, c++]

---

# LC 103. Binary Tree Zigzag Level Order Traversal

### [Problem link](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)

###### tags: `leedcode` `medium` `c++` `BFS`

Given the <code>root</code> 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).

**Example 1:** 
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" style="width: 277px; height: 302px;" />
```
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
```

**Example 2:** 

```
Input: root = [1]
Output: [[1]]
```

**Example 3:** 

```
Input: root = []
Output: []
```

 **Constraints:** 

- The number of nodes in the tree is in the range <code>[0, 2000]</code>.
- <code>-100 <= Node.val <= 100</code>

## Solution 1 - BFS
#### C++
```cpp=
/**
 * 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>> ans;
        bool isEven = false;
        queue<TreeNode *> q;
        if (root != nullptr) {
            q.push(root);
        }
        while (!q.empty()) {
            int sz = q.size();
            vector<int> level;
            for (int i = 0; i < sz; i++) {
                TreeNode *node = q.front();
                q.pop();
                level.push_back(node->val);
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
            if (isEven) {
                reverse(level.begin(), level.end());
            }
            isEven = !isEven;
            ans.push_back(level);
        }
        return ans;
    }
};
```

>### Complexity
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(n)             |

## Note
x
