My BST code is not showing any output and there is no error? can someone please explain what I'm doing wrong? I'm using Visual Code I ran the code on multiple online compilers as well but just got a segmentation error and on vs code it's not showing anything at all.
#include <iostream>
#include <type_traits>
using namespace std;
class node
{
public:
int data;
node *left, *right;
node(int data){
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
class BST{
public:
node* addNode(int data){
node* newNode = new node(data);
return newNode;
}
void Inorder(node* root){
if(root == NULL)
return;
Inorder(root -> left);
cout << root -> data << "\t";
Inorder(root -> right);
}
node* insert(node* newNode, int data){
if(newNode == NULL)
return addNode(data);
if(data < newNode -> data)
newNode -> left = insert(newNode, data);
else if(data > newNode -> data)
newNode -> right = insert(newNode, data);
return newNode;
}
};
int main(){
node *root = NULL;
BST objbst;
root = objbst.insert(root, 8);
root = objbst.insert(root, 3);
root = objbst.insert(root, 1);
root = objbst.insert(root, 6);
root = objbst.insert(root, 7);
root = objbst.insert(root, 10);
root = objbst.insert(root, 14);
root = objbst.insert(root, 4);
cout << "Inorder traversal: ";
objbst.Inorder(root);
}
if I'm doing something wrong then can someone please tell me what I'm doing wrong?
modify the insert function as given below and then run your code, you need to call left or right instances of node(based on condition) when traversing the tree recursively!
node* insert(node* Node, int data){
if(Node == NULL)
return addNode(data);
if(data < Node -> data)
Node -> left = insert(Node->left, data);
else if(data > Node -> data)
Node -> right = insert(Node->right, data);
return Node;
}