0

//Here is the function of inserting nodes.I tried using strcmp but its still not working.

void BinarySearchTree::insert(char* d)  
    {
            tree_node* t = new tree_node;
            tree_node* parent;
        strcpy(t->data,d);
            t->left = NULL;
            t->right = NULL;
            parent = NULL;
          // is this a new tree?
          if(isEmpty()) root = t;
          else
          {
                //Note: ALL insertions are as leaf nodes
                tree_node* curr;
                curr = root;
                // Find the Node's parent
            while(curr)
            {
				cout<<"current"<<curr->data<<endl;
                parent = curr;
				if(strcmp(t->data,curr->data)==0)
				{
					cout<<"duplicat nodes";
					exit(1);
				}
                if(strcmp(t->data,curr->data)>0) curr = curr->right;
                else curr = curr->left;
            }

            if(strcmp(t->data,parent->data)<0)
                   parent->left = t;
            else
                   parent->right = t;
          }
          count++;
    }
2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by mitrmkar
0

//Here is the function of inserting nodes.I tried using strcmp but its still not working.

What do you mean by "still not working"?

Do you really want to use exit() there? I.e. your program gets terminated when duplicate data is encountered.

A suggestion regarding initialization of a tree_node

struct tree_node
{
  // default constructor
  tree_node() 
  : left(NULL), right(NULL)
  {
    // pointers are now initialized to NULL
  }
};

// So that would make somewhat cleaner code ..
tree_node* t = new tree_node;
// t->left and t->right are now automatically NULL
...

Then you might expand that even little more and also pass the data through the constructor.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.