Here is a code for BST that I have written , that does not use pass by reference. Help me to find flaws in its design. Also I do not like the function getReqNodes
, can it be made more elegant.
#include <iostream>
using namespace std;
struct node {
int data;
node* left = nullptr;
node* right = nullptr;
node(int d , node *l = nullptr, node *r = nullptr){
data = d;
left = l;
right = r;
}
};
node* insertVal(node* n, int val) {
if (n == nullptr) {
n = new node(val);
n->data = val;
return n;
}
else if (val < n->data){
return new node(n->data, insertVal(n->left,val), n->right);
}
else if(val > n->data) {
return new node(n->data, n->left, insertVal(n->right, val));
}
else{
return new node(val, n->left, n->right);
}
}
int minVal(node* n) {
if (n == nullptr) return -10000;
else if (n->left == nullptr) return n->data;
else return minVal(n->left);
}
node* getReqNodes(node *t, node *q){
if(q == nullptr){return t;}
else{
t = insertVal(t,q->data);
t = getReqNodes(t,q->left);
t = getReqNodes(t,q->right);
return t;
}
}
node* removeVal(node *n, int v){
if (n == nullptr){return n;}
else if(v < n->data){
return new node(n->data, removeVal(n->left,v), n->right);
}
else if(v > n->data){
return new node(n->data, n->left, removeVal(n->right, v));
}
else{
node *j = n;
//attaching right subtree to the left subtree
node *p = getReqNodes(n->left, n->right);
delete j;
return p;
}
}
void printTree(node* n) {
if (n == nullptr) { return; }
printTree(n->left);
cout << n->data << " ";
printTree(n->right);
}
int main() {
node* p = nullptr;
for(int i = 0; i < 15; ++i){
p = insertVal(p, rand()%15);
}
printTree(p);cout<<endl;cout<<endl;
node *foo = removeVal(p, 149);
printTree(foo);
return 0;
}
std::cout
. You need to work on encapsulation and how classes work. \$\endgroup\$