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

leetcode 103. Binary Tree Zigzag Level Order Traversal

时间:2015-02-17 19:52:54      阅读:169      评论: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.

[Solution]

 1 vector<vector<int> > zigzagLevelOrder(TreeNode *root) 
 2     {
 3         vector<vector<int> > result;
 4         vector<int> line;
 5         queue<TreeNode *> qtree;
 6         TreeNode *visit = root;
 7         int current_level_size = 1, next_level_size = 0;
 8         int level = 0;
 9         
10         if (visit != NULL)
11             qtree.push(visit);
12         while (!qtree.empty())
13         {
14             visit = qtree.front();
15             qtree.pop();
16             current_level_size--;
17             line.push_back(visit->val);
18             
19             if (visit->left != NULL)
20             {
21                 qtree.push(visit->left);
22                 next_level_size++;
23             }
24             if (visit->right != NULL)
25             {
26                 qtree.push(visit->right);
27                 next_level_size++;
28             }
29             if (current_level_size == 0) // all this level nodes are visited.
30             {
31                 if (level & 0x01)
32                     reverse(line.begin(), line.end());
33                 level++;
34                 result.push_back(line);
35                 line.clear();
36                 current_level_size = next_level_size;
37                 next_level_size = 0;
38             }
39         }
40         
41         return result;
42     }

 

leetcode 103. Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4295404.html

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