user1851359
user1851359

Reputation: 139

Insert element into a binary tree in c

I would like to ask a question about inserting element into a binary tree, I need to insert element into table. However, I think I misunderstood about the pointer or something, that i am not able to create the binary tree.

The insert function is called by another file which contain the main function, therefore insert function is called regularly until all element is inserted. The insert function then calls the sub_insert to insert all the element. When i tried to read the binary tree, its empty. Can anyone suggest what to fix?

   typedef struct node * tree_ptr;
   /*typedef char* Key_Type; */

   struct node {
     Key_Type element; // only data is the key itself
     tree_ptr left, right;
     int depth;
   };

   struct table {
     tree_ptr head; // points to the head of the tree


   };
   struct table head,tail;



   struct node* newNode(Key_Type key){
      struct node* node=(struct node*)malloc(sizeof(struct node));
      node->element=key;
      node->left=NULL;
      node->right=NULL;
      return (node);
   }

   tree_ptr sub_insert(Key_Type key, struct node *node, Table table) {
      printf("reading... %s\n", key);

     if(node==NULL)
       return(newNode(key));

     else
     {
       if(key <= node->element){
         printf("inserted");
         node->left = sub_insert(key, node->left, table);
       }else{
         node->right = sub_insert(key, node->right, table);
       } 
         return node;
     }
   }

   Table insert(Key_Type key, Table table) {

        struct node* root=NULL;
        root=sub_insert(key, root, table);

        return table;
   }

Upvotes: 0

Views: 1394

Answers (2)

Jeremy SH
Jeremy SH

Reputation: 126

Like Joachim said, your problem is that you're always using NULL as a root node:

    struct node* root=NULL;
    root=sub_insert(key, root, table);

I'm guessing, but it seems like you want to use table.head as the starting node:

    root=sub_insert(key, table.head, table);

Dunno whether table is a pointer or not, so I just used dot notation.

In any case, you absolutely need a valid root node before you traverse with sub_insert(), otherwise all your new nodes will just dangle in memory.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

Lets take a look at the insert function:

Table insert(Key_Type key, Table table) {
    struct node* root=NULL;
    root=sub_insert(key, root, table);
    return table;
}

Here you declare a root node, and use it in the call to sub_insert. You then return the unknown variable table, which is never modified in sub_insert. This means that the node you just created is lost.

Upvotes: 0

Related Questions