Question

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.

Était-ce utile?

La solution

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top