Repository navigation
Expand file tree
/
Copy pathday22.cpp
More file actions
93 lines (89 loc) · 2.12 KB
/
Copy pathday22.cpp
File metadata and controls
93 lines (89 loc) · 2.12 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
#include <iostream>
#include <algorithm>
using namespace std;
class Node{
public:
int value;
Node* right;
Node* left;
Node (int v){
value=v;
left=nullptr;
right=nullptr;
}
};
class BST{
public:
Node* root;
BST(){
root=nullptr;
}
void insert(int value){
if (root==nullptr){
root=new Node(value);
}
else {
insertHelper(root,value);
}
}
void insertHelper(Node* node,int value){
if (value<node->value){
if (node->left==nullptr){
node->left=new Node(value);
} else {
insertHelper(node->left,value);
}
} else {
if (node->right==nullptr){
node->right=new Node(value);
} else {
insertHelper(node->right,value);
}
}
}
bool search(Node* node,int value){
if (node == nullptr){
cout<<"value not found"<<endl;
return false;
}
if (node->value==value){
cout<<"value found"<<endl;
return true;
}
else if (node->value<value){
return search(node->right,value);
}
else {
return search(node->left,value);
}
}
void inorder(Node* node){
if (node != nullptr){
inorder(node->left);
cout<<node->value<<endl;
inorder(node->right);
}
}
int height(Node* node){
if (node == nullptr){
return 0;
}
return 1+ max(height(node->right),height(node->left));
}
};
int main(){
BST tree;
int values[]={8,5,7,4,3,10,1,6,14,99,50,11};
for (int v:values){
tree.insert(v);
}
cout<<"root: "<<tree.root->value<<endl;
cout<<"root->left: "<<tree.root->left->value<<endl;
cout<<"root->right: "<<tree.root->right->value<<endl;
cout<<tree.search(tree.root,6)<<endl;
cout<<tree.search(tree.root,9)<<endl;
tree.inorder(tree.root);
cout<<endl;
cout<<"height: "<<tree.height(tree.root)<<endl;
return 0;
}