forked from 790hanu/Annex-qr-code-simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_search_tree.cpp
110 lines (105 loc) · 2.23 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
#include <iostream>
#include <queue>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
this->data = d;
this->left = NULL;
this->right = NULL;
}
};
Node *insertIntoBST(Node *root, int d) {
if (root == NULL) {
root = new Node(d);
return root;
}
if (d > root->data) {
root->right = insertIntoBST(root->right, d);
} else {
root->left = insertIntoBST(root->left, d);
}
return root;
}
Node *deleteFromBST(Node *root, int val) {
// base case
if (root == NULL) {
return root;
}
if (root->data == val) {
// 0 child
if (root->right == NULL && root->left == NULL) {
delete root;
return NULL;
}
// 1 child
// left child
if (root->left != NULL && root->right == NULL) {
Node *temp = root->left;
delete root;
return temp;
}
// right child
if (root->right != NULL && root->left == NULL) {
Node *temp = root->right;
delete root;
return temp;
}
// 2 child
if (root->right != NULL && root->left != NULL) {
int min = minVal(root->right)->data;
root->data = min;
root->right = deleteFromBST(root->right, min);
return root;
}
// o(n) time and space both
} else if (root->data > val) {
root->left = deleteFromBST(root->left, val);
return root;
} else {
root->right = deleteFromBST(root->right, val);
return root;
}
}
void levelOrderTraversal(Node *root) {
queue<Node *> q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
Node *temp = q.front();
q.pop();
if (temp == NULL) { // purana level complete traverse ho chuka hai
cout << endl;
if (!q.empty()) { // queue still has some child nodes
q.push(NULL);
}
} else {
cout << temp->data << " ";
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
}
}
void takeInput(Node *&root) {
int data;
cin >> data;
while (data != -1) {
root = insertIntoBST(root, data);
cin >> data;
}
}
int main() {
Node *root = NULL;
cout << "enter data " << endl;
takeInput(root);
cout << "printing BST" << endl;
levelOrderTraversal(root);
}
// insertion in BST logn