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.

有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top