I am trying to implement insert function in binary search tree. I was able to do it without using recursion(the commented part). But while doing it using recursion my root is not geting updated Following is my code :
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node *left;
Node *right;
Node(int x){
data = x;
left = NULL;
right = NULL;
}
};
void insert(Node *root,int data){
// Node *temp = root;
// while (temp){
// if (data == temp->data )
// return;
// if (data > temp->data){
// cout<<temp->data<<endl;
// if(temp->right == NULL){
// Node *node = new Node(data);
// temp->right = node;
// return ;
// }
// temp = temp->right;
// }
// else {
// if (!temp->left){
// Node *node = new Node(data);
// temp->left = node;
// return ;
// }
// temp = temp->left;
// }
// }
if(root == NULL){
root = new Node(data);
cout<<root->data<<endl;
return;
}
// Node *temp = root;
if(data >= root->data ){
insert(root->right,data);
}
else{
insert(root->left,data);
}
return;
}
void inorder( Node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->data);
inorder(root->right);
}
}
int main(){
Node *root = NULL;
insert(root,45);
if(root == NULL)
cout<<"hello"<<endl;
// cout<<root->data;
// insert(root,8);
inorder(root);
// cout<<root->data;
}
On running root is remaining NULL, which suppposed to get updated. Any help will be appreciated.