-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZigZag Level Order Traversal BT.cpp
86 lines (57 loc) · 1.59 KB
/
ZigZag Level Order Traversal BT.cpp
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<vector<int> > Solution::zigzagLevelOrder(TreeNode* root) {
vector<vector<int> >ans;
if(root==NULL)
return ans ;
stack<TreeNode*>st1 ;
stack<TreeNode*>st2 ;
st1.push(root) ;
int turn=0; // stack 1 turn
while( (!st1.empty()) ||(!st2.empty()) )
{vector<int>ans1 ;
if(turn==0)
{
while(!st1.empty())
{
TreeNode *temp=st1.top() ;
st1.pop() ;
ans1.push_back(temp->val);
// cout<<(temp->data)<<" ";
if(temp->left){
st2.push(temp->left);
}
if(temp->right)
{
st2.push(temp->right) ;
}
}
turn =1 ;
}
else{
while(!st2.empty()) {
TreeNode *temp=st2.top() ;
st2.pop() ;
ans1.push_back(temp->val) ;
// cout<<(temp->data)<<" ";
if(temp->right)
{
st1.push(temp->right) ;
}
if(temp->left){
st1.push(temp->left);
}
}
turn =0;
}
ans.push_back(ans1);
}
return ans ;
}