-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.cpp
More file actions
146 lines (124 loc) · 1.99 KB
/
tree.cpp
File metadata and controls
146 lines (124 loc) · 1.99 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include<iostream>
using namespace std;
struct Node{
int info;
Node * left;
Node * right;
} *root, *save, *newptr, *nptr;
void Insert(Node * ptr, Node * np)
{
if(root == NULL)
{
root = np;
}
else{
if(np -> info < ptr -> info)
{
if(ptr -> left == NULL)
ptr -> left = np;
else
Insert(ptr -> left, np);
}
if(np -> info > ptr -> info)
{
if(ptr -> right == NULL)
ptr -> right = np;
else
Insert(ptr -> right, np);
}
}
cout<<root->info;
}
Node * Create_new_node(int n)
{
nptr = new Node;
nptr -> left = NULL;
nptr -> right = NULL;
nptr -> info = n;
return nptr;
}
void Search(Node * ptr, int item)
{
if(item == root -> info)
{
cout<<"\nFound";
return;
}
while(ptr != NULL)
{
if(item < ptr -> info)
ptr = ptr -> left;
else
ptr = ptr -> right;
if(item == ptr -> info)
{
cout<<"\nFound!!";
return;
}
}
}
void inorder(Node * ptr)
{
if(ptr != NULL)
{
inorder(ptr -> left);
cout<< ptr -> info;
inorder(ptr -> right);
}
}
void preorder(Node * ptr)
{
if(ptr != NULL)
{
cout<<ptr -> info;
preorder(ptr -> left);
preorder(ptr -> right);
}
}
void postorder(Node * ptr)
{
if(ptr != NULL)
{
postorder(ptr -> left);
postorder(ptr -> right);
cout<< ptr -> info;
}
}
int main()
{
int ch1, item;
char ch2;
root = NULL;
do
{
cout<<"Enter your choice"<<endl
<<"1.Insert"<<endl
<<"2.Search"<<endl
<<"3.Inorder traversal"<<endl
<<"4.Preorder traversal"<<endl
<<"5.Postorder traversal"<<endl;
cin>>ch1;
if(ch1==1)
{
cout<<"\nEnter the information for the new node";
cin>>item;
newptr = Create_new_node(item);
Insert(root, newptr);
}
if(ch1 == 2)
{
cout<<"\nEnter the item to be searched for: ";
cin>>item;
Search(root, item);
}
if(ch1 == 3)
inorder(root);
if(ch1 == 4)
preorder(root);
if(ch1 == 5)
postorder(root);
cout<<"\nDo you want to continue? (y/n)";
cin>>ch2;
}while(ch2 == 'y');
return 0;
}