# 103. Binary Tree Zigzag Level Order Traversal

## 1.問題

* 給予一個binary tree, 回傳一個zigzag level order traversal的node's序列 (例如, 從左到右, 從leaf到root的方向層層排列)

![](/files/-LH3-JbNo5kNGSJX4lsr)

## 2.想法

* 可用level-order traversal, 廣度優先搜尋(BFS)的概念:
  * 1.先將root node放入一開始的queue
  * 2.queue當前中的每一個元素若有子樹的, 則加入queue中 (等待下一次)與Binary Tree Level Order Traversal 的解法相同, 但是用一個flag來控制方向
* 向前放入元素

```
v.insert(v.begin(), value);
```

* 向後放入元素

```
 v.push_back(value);
```

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        levelOrder(res, root);
        return res;
    }
private:
    void levelOrder(vector<vector<int>>& res, TreeNode* root) {
        if (!root) {
            return;
        }
        
        queue<TreeNode*> q;
        q.push(root);
        int cnt = 1;
        while (!q.empty()) {
            int size = q.size();
            vector<int> record;
            for (int i = 0; i < size; i++) {
                TreeNode* front;
                front = q.front();
                q.pop();
                if (cnt % 2) {
                    record.push_back(front->val);
                } else {
                    record.insert(record.begin(), front->val);
                }
                
                if (front->left) {
                    q.push(front->left);
                }
                if (front->right) {
                    q.push(front->right);
                }   
            }
            cnt++;
            res.push_back(record);
        }
    }
 };
```

## 4.Performance

![](/files/-LH2y4kzOBY0JIj5VfdG)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/103.-binary-tree-zigzag-level-order-traversal.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
