简体   繁体   English

插入二叉树指针错误

[英]Insertion in a binary tree pointer fault

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. 在此代码中,如果该节点为空,则将其发送到newnode函数,并为其分配内存和数据。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM