0

Below is my code for BST insertion. I want to use void return type for insert, instead of the regular way of using 'struct node*' as its return type. I am unable to find an error or logical error in this. Can someone explain in detail as to why isn't my code working?

#include<iostream>

using namespace std;

struct node
{
    int val;
    node *left, *right;
};

void ins(int key, node *nroot)
{
    if(nroot == NULL)
    {
        node *temp= new node;
        temp->val=key;
        temp->left=NULL;
        temp->right=NULL;
        nroot=temp;
    }
    else if(key > nroot->val)
    {
        ins(key, nroot->right);
    }
    else
    {
        ins(key, nroot->left);
    }
}

void print(node *nroot)
{
    if(nroot!=NULL)
    {
        print(nroot->left);
        cout<<nroot->val;
        print(nroot->right);
    }
}

main()
{
    int n;
    cin>>n;
    node *root= new node;
    int x;
    cin>>x;
    root->left=NULL;
    root->right=NULL;
    root->val=x;
    for(int i=1;i<n;i++)
    {
        cin>>x;
        ins(x, root);
    }
    print(root);
}
  • `nroot=temp;` assigns to the local variable; this assignment is not visible to the caller. When you call `ins(key, nroot->right)`, whatever happens inside `ins`, `nroot->right` is still `NULL`. – Igor Tandetnik Jul 26 '20 at 17:29
  • In `void ins(int key, node *nroot)` `nroot` is passed by value, not by reference. Yes, it is a pointer, but a pointer is a plain old variable whose value is the address of another object. That other object is passed by reference. The pointer itself is still passed by value, so it you point it somewhere else, you have merely changed a copy. – user4581301 Jul 26 '20 at 17:29

1 Answers1

0

The problem with your code is, whenever you make changes to the variable nroot (not changes to values nroot is pointing to) in the insert function, the changes will be local to the insert function. So they won't appear on the outside of the insert function. So that's not the correct way.

For doing this, you can either return nroot or use double pointer or the reference to the node

Sai Sreenivas
  • 1,690
  • 1
  • 7
  • 16