-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search_tree.cpp
131 lines (100 loc) · 2.46 KB
/
binary_search_tree.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
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
#include <iostream>
#include <queue>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int data): data(data), left(nullptr), right(nullptr) {}
};
void insertNode(Node**, int);
void printTree(Node*);
void levelOrder(Node*);
bool searchNode(Node*, int);
int min(Node*);
int max(Node*);
int height(Node*);
int main() {
Node *root = new Node(15);
int arr[6] = {10, 20, 7, 13, 17, 25};
for (int i : arr) {
insertNode(&root, i);
}
cout << "Preorder Traversal: \n";
printTree(root);
cout << "\n\n";
cout << "Level Order Traversal: \n";
levelOrder(root);
cout << "Max: " << max(root) << ", Min: " << min(root) << "\n";
cout << "Height of the tree: " << height(root) << "\n";
return 0;
}
void insertNode(Node **root, int data) {
if ((*root) == nullptr) {
(*root) = new Node(data);
return;
}
if (data < (*root) -> data) {
insertNode(&((*root) -> left), data);
}
else {
insertNode(&((*root) -> right), data);
}
}
void printTree(Node *root) {
if (root != nullptr) {
cout << root -> data << " ";
printTree(root -> left);
printTree(root -> right);
}
}
bool searchNode(Node *root, int data) {
if (root == nullptr) {
return false;
}
if (root -> data == data) {
return true;
}
if (data < root -> data) {
return searchNode(root -> left, data);
}
return searchNode(root -> right, data);
}
int min(Node *root) {
if (root == nullptr) {
return -1;
}
while (root -> left != nullptr) {
root = root -> left;
}
return root -> data;
}
int max(Node *root) {
if (root == nullptr) {
return -1;
}
while (root -> right != nullptr) {
root = root -> right;
}
return root -> data;
}
void levelOrder(Node *root) {
if (root == nullptr) return;
queue<Node*> Q;
Node *current = nullptr;
Q.push(root);
while (!Q.empty()) {
current = Q.front();
cout << current -> data << " ";
if (current -> left != nullptr) Q.push(current -> left);
if (current -> right != nullptr) Q.push(current -> right);
Q.pop();
}
cout << "\n";
}
int height(Node *root) {
if (root == nullptr) return -1;
int max_height = (height(root -> left) > height(root -> right)) ? height(root -> left) : height(root -> right);
return max_height + 1;
}