-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spiral Order Traversal of a Binary Tree
52 lines (47 loc) · 1.22 KB
/
Spiral Order Traversal of a Binary Tree
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
vector<int> spiralOrder(BinaryTreeNode<int> *root)
{
// Write Your Code Here.
vector <int> ans ;
if(root == NULL)
return ans ;
deque <BinaryTreeNode<int> *> dq ;
dq.push_back(root) ;
int d = 0 ;
while(!dq.empty())
{
int sz = dq.size() ;
for(int i = 0 ; i < sz ; i++)
{
if(d == 1)
{
BinaryTreeNode<int> * f = dq.back() ;
dq.pop_back() ;
if(f->right)
{
dq.push_front(f->right) ;
}
if(f->left)
{
dq.push_front(f->left) ;
}
ans.push_back(f->data) ;
}
if(d == 0)
{
BinaryTreeNode<int> * f = dq.front() ;
dq.pop_front() ;
if(f->left)
{
dq.push_back(f->left) ;
}
if(f->right)
{
dq.push_back(f->right) ;
}
ans.push_back(f->data) ;
}
}
d = (d + 1)%2 ;
}
return ans ;
}