-4

I have two structs that represent a node of a binary search tree and a bst. Calling the add method the first time the output is as expected: tree is null, but why is it still: tree is null after I call it the second time?

If I send as parameter to the add method the whole bst, it works.

#include <iostream>

using namespace std;

struct node
{
    int data;
    node* right = NULL;
    node* left  = NULL;
};

struct bst
{
    node* root = NULL;
};



void add(node* tree) 
{

    if (tree == NULL)
    {
        cout << "Tree is NULL "<<endl;
        tree = new node;
    }
    else cout << "Not NULL"<<endl;
}

int main()
{
    bst* tree = new bst;
    add(tree->root);
    add(tree->root);
    system("pause");
    return 0;

}
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Dan
  • 274
  • 6
  • 14

2 Answers2

1

You can't pass tree back out of the function unless you declare it as the address of the pointer like this:

    void add(node** tree) {
        if ( tree == NULL ) {
          return;
        }
        if (*tree == NULL) {
          cout << "Tree is NULL " << endl;
          *tree = new node;
        } else {
          cout << "Not NULL" << endl;
        }       
    }
SPlatten
  • 5,334
  • 11
  • 57
  • 128
0

You're passing the node itself instead of its address. Try

void add(node** tree)
{
  if (*tree == NULL)
  {
      cout << "Tree is NULL "<<endl;
      *tree = new node;
  }
  else cout << "Not NULL"<<endl;
}

int main()
{
  bst* tree = new bst;
  add(&(tree->root));
  add(&(tree->root));
  system("pause");
  return 0;
}
Robert Kock
  • 5,795
  • 1
  • 12
  • 20