首页 > 其他 > 详细

【树】103. 二叉树的锯齿形层次遍历

时间:2020-05-02 15:01:52      阅读:67      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

 

 

 

解答:

这个题目和上一题目没有太大的区别,设置一个标志位,以决定从左到右还是从右到左。

 1 //小集合和大集合均OK
 2 class Solution {
 3 public:
 4     vector<vector<int> > zigzagLevelOrder(TreeNode *root)
 5     {
 6         vector< vector<int> > result;
 7         if (root == NULL)
 8         {
 9             return result;
10         }
11         
12         queue<TreeNode*> q;
13         q.push(root);
14         
15         vector<int> tmp(0);
16         
17         int count = 1;
18         int level = 0;
19         
20         int flag = 1; //标志
21         while(!q.empty())
22         {
23             tmp.clear();
24             level = 0;
25             
26             for (int i = 0; i < count; ++i)
27             {
28                 root = q.front();
29                 q.pop();
30                 tmp.push_back(root->val);
31                 
32                 if (root->left != NULL)
33                 {
34                     q.push(root->left);
35                     ++level;
36                 }
37                 if (root->right != NULL)
38                 {
39                     q.push(root->right);
40                     ++level;
41                 }
42             }
43             count = level;
44             
45             if(flag % 2 == 0)
46             {
47                 reverse(tmp.begin(), tmp.end());
48             }
49             flag++;
50             
51             result.push_back(tmp);
52         }
53         //reverse(result.begin(), result.end());
54         return result;
55     }
56 };

 

 

 

 

【树】103. 二叉树的锯齿形层次遍历

原文:https://www.cnblogs.com/ocpc/p/12817567.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!