문제

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