1

The code given below is the code that I have written for insertion in a binary tree. The code works for the root node but is not working for its children. I know that I have to pass a reference to the root node while insertion in the children but do not know how to implement it. What is to be changed?

#include <stdio.h>
#include <stdlib.h>

struct bintree
{
int data;
struct bintree *left;
struct bintree *right;
};

typedef struct bintree btree;

btree* newnode(btree *node, int data)
{
    node=(btree*)malloc(sizeof(btree));
    node->data=data;
    node->left=NULL;
    node->right=NULL;
    return node;
}

btree* insert(btree *node, int data)
{
    if(node==NULL)
    {
        return (newnode(node, data));
    }
    else
    {
        if(data<=node->data)
        {
            insert(node->left, data);
            return(node);
        }
        else
        {
            insert(node->right, data);
            return(node);
        }
    }
}

int main()
{
    btree *root=NULL;
    root=insert(root, 5);
    insert(root, 3);
    insert(root, 6);
    return 0;
}

In this code the node, if it is null, is sent to newnode function and is assigned memory and data. In other cases the insert function is used.

1
  • Please avoid the use of malloc. Use operator new instead. Commented Jul 17, 2013 at 6:44

1 Answer 1

1

Change this:

 if(data<=node->data)
    {
        insert(node->left, data);
        return(node);
    }
    else
    {
        insert(node->right, data);
        return(node);
    }

to:

    if(data<=node->data)
    {
        node->left = insert(node->left, data);
    }
    else
    {
        node->right = insert(node->right, data);
    }
    return (node);

also the code in your main should be:

root = insert(root, 5);
root = insert(root, 3);
root = insert(root, 6);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.