-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path103.cpp
More file actions
87 lines (84 loc) · 1.61 KB
/
103.cpp
File metadata and controls
87 lines (84 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root==NULL)
return res;
queue<pair<TreeNode*,int>>q;
q.push(make_pair(root,0));
while(!q.empty())
{
TreeNode *t=q.front().first;
int level=q.front().second;
if(level==res.size())
res.push_back(vector<int>());
res[level].push_back(t->val);
if(t->left!=NULL)
q.push(make_pair(t->left,level+1));
if(t->right!=NULL)
q.push(make_pair(t->right,level+1));
}
for(int i=0;i<res.size();i++)
{
if(i%2==1)
reverse(res[i].begin(),res[i].end());
}
return res;
}
};*/
class Solution{
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root)
{
vector<int> row;
vector<vector<int>> v;
queue<TreeNode*> q;
if(root==NULL)
return v;
q.push(root);
TreeNode *temp;
int level=0;
while(!q.empty())
{
int size=q.size(); //下一行所有元素数
while(size--)
{
temp=q.front();
q.pop();
row.push_back(temp->val);
if(temp->left!=NULL)
q.push(temp->left);
if(temp->right!=NULL)
q.push(temp->right);
}
if(level%2==1) //奇数行 逆置
{
int n=row.size();
for(int i=0;i<n/2;i++)
swap(row[i],row[n-i-1]);
}
v.push_back(row);
level++;
row.clear();
}
return v;
}
};