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]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

 1 class Solution {
 2 public:
 3     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
 4         vector<vector<int> >res;
 5         if(root==NULL) return res;
 6 
 7         vector<int> level;
 8         queue<TreeNode* > q;
 9         q.push(root);
10 
11         int cnt=1;
12         int curcnt=0;
13 
14         bool order=true;
15 
16         while(!q.empty())
17         {
18             TreeNode *node=q.front();
19             q.pop();
20             level.push_back(node->val);
21             if(node->left)
22             {
23                 q.push(node->left);
24                 curcnt++;
25             }
26             if(node->right)
27             {
28                 q.push(node->right);
29                 curcnt++;
30             }
31 
32             cnt--;
33             if(cnt==0)
34             {
35                 if(order)
36                 {
37                     res.push_back(level);
38                 }else{
39                     reverse(level.begin(),level.end());
40                     res.push_back(level);
41                 }
42 
43                 order=!order;
44                 level.clear();
45                 cnt=curcnt;
46                 curcnt=0;
47             }
48         }
49         return res;
50     }
51 };

 

posted on 2015-06-06 22:47  黄瓜小肥皂  阅读(146)  评论(0编辑  收藏  举报