-
Notifications
You must be signed in to change notification settings - Fork 25
/
SpiralFormoftree.cpp
89 lines (77 loc) · 1.28 KB
/
SpiralFormoftree.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
87
88
89
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int k)
{
data=k;
left=right=NULL;
}
};
void Spiral(Node *root)
{
if(root==NULL)
return;
queue<Node *> q;
q.push(root);
stack<int> st;
bool reverse= false;
while(!q.empty())
{
int size=q.size();
if(reverse==false)
{
for(int i=0;i<size;i++)
{
Node *curr= q.front();
q.pop();
cout<<curr->data<<" ";
if(curr->left!=NULL)
q.push(curr->left);
if(curr->right!=NULL)
q.push(curr->right);
}
}
else
{
for(int i=0;i<size;i++)
{
Node *curr= q.front();
q.pop();
st.push(curr->data);
if(curr->left!=NULL)
q.push(curr->left);
if(curr->right!=NULL)
q.push(curr->right);
}
}
if(reverse==true)
{
while(!st.empty())
{
cout<<st.top()<<" ";
st.pop();
}
}
reverse=!reverse;
}
}
int main()
{
Node *root;
root=new Node(2);
root->left=new Node(7);
root->left->left=new Node(3);
root->left->right=new Node(6);
root->left->right->right=new Node(11);
root->left->right->left=new Node(5);
root->right=new Node(8);
root->right->right=new Node(9);
root->right->right->left=new Node(4);
Spiral(root);
return 0;
}