-
Notifications
You must be signed in to change notification settings - Fork 1
/
103. Binary Tree Zigzag Level Order Traversal
63 lines (61 loc) · 1.54 KB
/
103. Binary Tree Zigzag Level Order Traversal
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root)
{
vector<vector<int>> l;
if(root==NULL)
return l;
TreeNode *a[2000];
a[0]=root;
int c=1,n,i,j=0,x=0;
while(c!=x)
{
vector<int> l1;
i=c-1;
n=x;
for(;i>=n;i--)
l1.push_back(a[i]->val);
if(j%2==0)
{
i=c-1;
n=x;
x=c;
for(;i>=n;i--)
{
if(a[i]->left!=NULL)
a[c++]=a[i]->left;
if(a[i]->right!=NULL)
a[c++]=a[i]->right;
}
}
else
{
i=c-1;
n=x;
x=c;
for(;i>=n;i--)
{
if(a[i]->right!=NULL)
a[c++]=a[i]->right;
if(a[i]->left!=NULL)
a[c++]=a[i]->left;
}
}
j++;
l.push_back(l1);
}
return l;
}
};