-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexp9.cpp
103 lines (82 loc) · 1.72 KB
/
exp9.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
92
93
94
95
96
97
98
99
100
101
102
103
#include <iostream>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
public:
node(int data){
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
node* insert(node* root , int data){
if(root==NULL){
return new node(data);
}
if(data>root->data){
root->right = insert(root->right , data);
}
else{
root->left = insert(root->left , data);
}
return root;
}
/*
int search(node* root,int data){
if(root==NULL){
return 0;
}
else if(data==root->data){
return 1;
}
if(data > root->data){
return search(root->right ,data);
}
else{
return search(root->left,data );
}
}
*/
void preorder(node*root){
if(root==NULL){
return;
}
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
node* search(node* root,int data){
if(root==NULL){
return NULL;
}
else if(data == root->data){
return root;
}
if(data > root->data){
return search(root->right,data);
}
else{
return search(root->left,data );
}
}
int main() {
node* root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
int value = 30;
// if (search(root, value)) {
// cout<<"Node with value "<<value<<" found in the BST."<<endl;
// } else {
// cout<<"Node with value "<<value<<"Not found in the BST."<<endl;
// }
preorder(search(root,value));
return 0;
}