Recursive insertion of BST
Asked Answered
I

6

6

I have made a function for insertion in BST using loops and it is working perfectly fine. Now, when iam writing to do it using recursion i don't know why it's not working properly, however the logic is correct according to me. It seems that no newnode is being added to the BST tree and head of the tree after coming out of the insertion function is again becoming NULL.

#include <iostream>
using namespace std;

class node{
public:
   int data;
   node *right;
   node *left;
   node(){
      data=0;
      right=NULL;
      left=NULL;
   }
};

class tree{
   node *head;
   int maxheight;
   void delete_tree(node *root);
public:
   tree(){head=0;maxheight=-1;}
   void pre_display(node* root);
   node* get_head(){return head;}
   void insert(int key,node* current);
};

void tree::insert(int key,node *current){
   if(current==NULL)
   {
      node *newnode=new node;
      newnode->data=key;
      current=newnode;
   }
   else{
      if(key<current->data)
         insert(key,current->left);
      else
         insert(key,current->right);
   }
   return;
}

void tree::pre_display(node *root){
   if(root!=NULL)
   {
      cout<<root->data<<" ";
      pre_display(root->left);
      pre_display(root->right);
   }
}

int main(){
   tree BST;
   int arr[9]={17,9,23,5,11,21,27,20,22},i=0;

   for(i=0;i<9;i++)
   BST.insert(arr[i],BST.get_head());

   BST.pre_display(BST.get_head());
   cout<<endl;

   system("pause");
   return 0;
}

Please tell me what should i change in the algorithm to make it work.

Ioneionesco answered 18/11, 2011 at 14:28 Comment(0)
D
3

In your insert function

void tree::insert(int key,node *current){
    if(current==NULL)
    {
        node *newnode=new node;
        newnode->data=key;
        current=newnode;
    }
    else{
        if(key<current->data)
            insert(key,current->left);
        else
            insert(key,current->right);
    }
    return;
}

you allocate a new node but never set BST::head to newly allocated head. So BST::get_head will always return null.

One way to fix this would be for insert to return a node. This would be root node in your case and set the BST::head to this value.

Divestiture answered 18/11, 2011 at 14:32 Comment(5)
But iam sending head pointer from main, and hence current will be same as the head in the first instance of recursion.Ioneionesco
You are passing a node* by value. If you pass it by reference BST::head will be updated correctlyDivestiture
But i want to keep BST head private.Ioneionesco
@Zohaib: does private mean for you that it should never change?Citronella
If you want to keep things private.... Node should be class private to BST and BST should only expose iterators to iterate the tree.Divestiture
S
3

Your recursion looks fine, but you don't actually add the node anywhere! You just recurse through the tree.

Edit You can change the insert method to take a pointer to a pointer, like this:

void tree::insert(int key, node **current)
{
    if(*current == NULL)
    {
        node *newnode = new node;
        newnode->data = key;
        *current = newnode;
    }
    else 
    {
        if(key < (*current)->data)
            insert(key, &(*current)->left);
        else
            insert(key, &(*current)->right);
    }
}

And in main call it like this:

BST.insert(arr[i], &BST.get_head());  // Note the ampersand (&)
Saintebeuve answered 18/11, 2011 at 14:33 Comment(4)
@Ioneionesco No, you just create a new node, you don't add it to the tree.Saintebeuve
Does'nt this statement:current=newnode; would add newnode to the tree.Ioneionesco
@Ioneionesco Oops, missread it. The indentation is not too good in my opinion.Saintebeuve
@Ioneionesco Yeah, getting a little tired over here, end of day, know what's wrong, will look at it later.Saintebeuve
K
0

you should try this

             node  tree:: insert ( int key , node * current )  {

                     if ( ! current ) {
                           node * newnode = new node ;
                           newnode -> key = key;
                           current = newnode ;
                      }
                    else if ( key < current -> key )  {
                        current -> left = insert ( key , current ->left 
                         }
                    else 
                       current -> right = insert ( key , current->right )
                return current ;
               }

it works fine....jsut update the head node every time whenver a new node is inserted and it will return the updated current node.

Kiel answered 3/1, 2016 at 6:29 Comment(0)
D
0

Just change your function as

void tree::insert(int key,node*& current){
  if(current==NULL)
  {
    node *newnode=new node;
    newnode->data=key;
    current=newnode;
  }
  else{
    if(key<current->data)
      insert(key,current->left);
    else
      insert(key,current->right);
  }
  return;
}

make your input pointer as a reference parameter.

Drennan answered 12/11, 2016 at 6:34 Comment(0)
S
0
struct node{
    node* left;
    node* right;
    int data;
};

node* root=NULL;

node* create(node* head,int val){
    if(head==NULL){
        node* nn=new node;
        nn->data=val;
        nn->left=NULL;
        nn->right=NULL;
        head=nn;
    }
    else if(val<head->data)
        head->left=create(head->left,val);
    else if(val>head->data)
        head->right=create(head->right,val);
    return head;
}

int main(){
    int num=0;
    cout<<"Enter value in tree or press -1 to Exit\n";
    while(num!=-1){
        cin>>num;
        if(num==-1){
            cout<<"\nTree Created\n";
            break;
        }
        else{
            root=create(root,num);
        }
    }
}

hope this code solves your problem

Slung answered 29/4, 2017 at 8:49 Comment(0)
A
0
void insertNode_recursive(int value, TreeNode *current)
{
    if (current == NULL)
    {
        if (current == NULL && isEmpty())
        {
            TreeNode *new_node = new TreeNode(value);
            current = new_node;
            root = new_node;
        }
        else
        {
            TreeNode *new_node = new TreeNode(value);
            current = new_node;
        }
    }
    else
    {
        if (value < current->getValue())
        {
            insertNode_recursive(value, current->getLeft());
        }
        else if (value > current->getValue())
        {
            insertNode_recursive(value, current->getRight());
        }
        else
        {
            cout << "\nDuplicate Value are Not Allowed\n";
        }
    }
}

This Code is Useful For Recursively Print the Tree Node

Ambala answered 21/1, 2021 at 8:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.