码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Binary Tree Zigzag Level Order Traversal

时间:2015-06-07 00:57:39      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

【leetcode】Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4557465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!