-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathamazoninterviewset33.cpp
More file actions
103 lines (92 loc) · 2 KB
/
Copy pathamazoninterviewset33.cpp
File metadata and controls
103 lines (92 loc) · 2 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//amazon internships set 1
//spiral order traversal
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data){
struct node* node=new(struct node);
node->data=data;
node->left=node->right=NULL;
return node;
}
struct node* insert(struct node* node,int data){
if(node==NULL)
return (newNode(data));
if(data<=node->data)
node->left=insert(node->left,data);
else
node->right=insert(node->right,data);
return node;
}
void printTree( node *tp, int spaces )
{
int i;
if( tp != NULL )
{
printTree( tp->right, spaces + 3 );
for( i = 0; i < spaces; i++ )
cout <<' ';
cout << tp->data << endl;
printTree( tp->left, spaces + 3 );
}
}
void spiralOrderTraversal(struct node* node){
stack<struct node*> current,next;//current level and next level
current.push(node);//pushing root initially
bool lefttoright=true;
while(!current.empty()){
struct node* currNode=current.top();
current.pop();
if(currNode){
cout<<currNode->data<<' ';
if(lefttoright){
next.push(currNode->left);
next.push(currNode->right);
}
else{
next.push(currNode->right);
next.push(currNode->left);
}
if(current.empty()){
cout<<endl;
lefttoright=!lefttoright;
stack<struct node*> temp=current;//swap
current=next;
next=temp;
}
}
}
}
void printPathArray(int path[],int len){
cout<<endl;
for(int i=0;i<len;i++)
cout<<path[i]<<' ';
}
void printPath(struct node* node,int path[],int len){
if(node==NULL)
printPathArray(path,len);
else{
path[len++]=node->data;
printPath(node->left,path,len);
printPath(node->right,path,len);
}
}
int main(){
struct node* root=NULL;
root=insert(root,4);
root=insert(root,2);
root=insert(root,5);
root=insert(root,1);
root=insert(root,3);
printTree(root,0);
cout<<"Spiral order traversal\n";
spiralOrderTraversal(root);
int path[100];
//printPath(root,path,0);
}