Repository navigation
Expand file tree
/
Copy pathBinary Search Tree.cpp
More file actions
106 lines (103 loc) · 2.08 KB
/
Copy pathBinary Search Tree.cpp
File metadata and controls
106 lines (103 loc) · 2.08 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
# include <bits/stdc++.h>
using namespace std;
struct BST
{
int data;
BST *left,*right;
}Node;
BST *GetNode()
{
BST *temp;
temp=(BST*)malloc(sizeof(BST));
temp->left=NULL;
temp->right=NULL;
return temp;
}
void InsertNode(BST *Root,BST *NewNode)
{
if(NewNode->data<Root->data)
{
if(Root->left==NULL)Root->left=NewNode;
else InsertNode(Root->left,NewNode);
}
else
{
if(Root->right==NULL)Root->right=NewNode;
else InsertNode(Root->right,NewNode);
}
return;
}
void PreorderPrint(BST *Root)
{
cout<<Root->data<<" ";
if(Root->left!=NULL)PreorderPrint(Root->left);
if(Root->right!=NULL)PreorderPrint(Root->right);
return;
}
void InorderPrint(BST *Root)
{
if(Root->left!=NULL)InorderPrint(Root->left);
cout<<Root->data<<" ";
if(Root->right!=NULL)InorderPrint(Root->right);
return;
}
void PostorderPrint(BST *Root)
{
if(Root->left!=NULL)PostorderPrint(Root->left);
if(Root->right!=NULL)PostorderPrint(Root->right);
cout<<Root->data<<" ";
return;
}
BST *SearchBST(BST *Root,int key)
{
while(Root!=NULL)
{
if(Root->data==key)return Root;
else if(key<Root->data)
{
if(Root->left!=NULL)
{
Root=Root->left;
}
else return NULL;
}
else if(key>Root->data)
{
if(Root->right!=NULL)
{
Root=Root->right;
}
else return NULL;
}
}
return NULL;
}
int main()
{
BST *Root,*NewNode;
Root=NULL;
for(int i=0;i<5;i++)
{
NewNode=GetNode();
cin>>NewNode->data;
if(Root==NULL)Root=NewNode;
else InsertNode(Root,NewNode);
}
PreorderPrint(Root);
cout<<endl;
InorderPrint(Root);
cout<<endl;
PostorderPrint(Root);
cout<<endl;
int Element;
cin>>Element;
if(SearchBST(Root,Element)==NULL)
{
cout<<"not found"<<endl;
}
else
{
cout<<"Element is found";
}
return 0;
}