-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5th.cpp
More file actions
155 lines (118 loc) · 2.86 KB
/
5th.cpp
File metadata and controls
155 lines (118 loc) · 2.86 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include<bits/stdc++.h>
using namespace std;
// 5
class Node {
public:
int data;
Node* left;
Node* right;
bool lthread;
bool rthread;
Node(int d) {
this->data = d;
this->left = NULL;
this->right = NULL;
this->lthread = false;
this->rthread = false;
}
};
void getInorder(Node* root, vector<Node*>& inorder){
if(root == NULL)
return;
getInorder(root->left, inorder);
inorder.push_back(root);
getInorder(root->right, inorder);
}
class BST {
Node* root;
bool isThreaded;
public:
BST() {
root = NULL;
isThreaded = false;
}
void insert(int d){
root = insertUtil(root, d);
}
bool search(int d){
return searchUtil(root, d);
}
bool searchUtil(Node* node, int d) {
if(node == NULL)
return false;
if(node->data == d)
return true;
if( d < node->data ){
return searchUtil(node->left, d);
}
else {
return searchUtil(node->right, d);
}
}
Node* insertUtil(Node* node, int d){
// base case
if(node == NULL){
node = new Node(d);
return node;
}
if( d > node->data ){
node->right = insertUtil(node->right, d);
}
else {
node->left = insertUtil(node->left, d);
}
}
// function to make the BST inorder threaded
void makeThreaded() {
vector<Node*> inorder;
getInorder(root, inorder);
for(int i=0; i<inorder.size(); i++){
Node* curr = inorder[i];
if(!curr->left && i-1 >= 0){
curr->left = inorder[i - 1];
curr->lthread = true;
}
if(!curr->right && i+1 < inorder.size()){
curr->right = inorder[i + 1];
curr->rthread = true;
}
}
isThreaded = true;
}
void threadedInTraversal() {
cout << "Inorder Traversal: ";
if(root == NULL){
cout << "Empty BST" << endl;
}
// If not threaded then make it threaded
if(!isThreaded){
makeThreaded();
}
// Go to leftmost node
Node* current = root;
while(current->left != NULL){
current = current->left;
}
// travel using right pointers
while(current != NULL){
cout << current->data << " ";
current = current->right;
}
cout << endl;
}
};
int main() {
int n;
cout << "Enter numbers to insert in BST: ";
cin >> n;
BST tree;
int val = -1;
cout << "Enter numbers : ";
for(int i=0; i<n; i++){
cin >> val;
tree.insert(val);
}
tree.makeThreaded();
tree.threadedInTraversal();
return 0;
}