-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST_Insertion.cpp
91 lines (83 loc) · 1.53 KB
/
BST_Insertion.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
90
91
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *left, *right;
Node(int value){
data=value;
left=right=NULL;
};
};
Node*insert(Node*root, int target){
if(!root){
Node*temp=new Node(target);
return temp;
}
//for left
if(target<root->data){
root->left=insert(root->left,target);
}
//for right
else{
root->right=insert(root->right,target);
}
return root;
}
void PreOrder(Node*root){
if(root==NULL){
return;
}
cout<<root->data;
PreOrder(root->left);
PreOrder(root->right);
};
void InOrder(Node*root){
if(root==NULL){
return;
}
InOrder(root->left);
cout<<root->data;
InOrder(root->right);
};
void PostOrder(Node*root){
if(root==NULL){
return;
}
PostOrder(root->left);
PostOrder(root->right);
cout<<root->data;
};
bool Search(Node*root, int target){
if(!root){
return 0;
}
if(root->data==target){
return 1;
}
if(root->data>target){
return Search(root->left,target);
}
else{
return Search(root->right,target);
}
};
int main()
{
int arr[]={2,6,3,9,18,24,4,7,26,30};
int i;
Node*root=NULL;
for(i=0;i<10;i++){
root=insert(root,arr[i]);
}
//CODE FOR TRAVERSAL
cout<<"PreOrder: ";
PreOrder(root);
cout<<"\nPostOrder: ";
PostOrder(root);
cout<<"\nInOrder: ";
InOrder(root);
//SEARCH
cout<<endl;
cout<<Search(root,26);
}