# LeetCode题目：Binary Tree Zigzag Level Order Traversal

By | 2012 年 12 月 10 日

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,#,#,15,7},

```    3
/ \
9  20
/  \
15   7
```

return its zigzag level order traversal as:

```[
[3],
[20,9],
[15,7]
]
```

```/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector > zigzagLevelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector > ret;
if(NULL == root) return ret;

queue que;
que.push(root);
que.push(NULL);//level end point

bool l2r = true;//left to right

vector level;
while(true) {
TreeNode *cur = que.front();
que.pop();
if(cur) {
level.push_back(cur->val);
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
} else {
if(l2r) {
ret.push_back(level);
} else {
vector temp;
for(int i = level.size() - 1 ; i >= 0; --i) {
temp.push_back(level[i]);
}
ret.push_back(temp);
}
level.erase(level.begin(),level.end());
l2r = !l2r;

if(que.size() == 0) break;
que.push(NULL);
}
}

return ret;
}
};
```