插入二叉搜索树 [英] Inserting in a Binary Search Tree

查看:113
本文介绍了插入二叉搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个二叉搜索树

struct BTNode
{
    int info;
    struct BTNode *left,*right;
};

我已经写了一个代码在树中插入一个节点

I've wrote a code to insert a node in the tree

void insert(struct BTNode *root,int data)
{
    struct BTNode *ptr;
    struct BTNode *n=malloc(sizeof(struct BTNode));
    n->info=data;
    n->left=NULL;
    n->right=NULL;
    if(root==NULL)
    root=n;
    else{
    ptr=root;
    while(ptr!=NULL){
        if(data<ptr->info){
            if(ptr->left==NULL)
            ptr->left=n;
            else
            ptr=ptr->left;
        }
        else if(data>ptr->info){
            if(ptr->right==NULL)
            ptr->right=n;
            else
            ptr=ptr->right;
        }
    }
    }
}

和main()函数

int main()
{
    struct BTNode *root=NULL;
    int choice,data;
    printf("\n1.Insert 2.Preorder 3.Exit\n");
    scanf("%d",&choice);
    switch(choice){
        case 1:
        printf("\nWrite the data: ");
        scanf("%d",data);
        insert(root, data);
        break;

但是当我尝试插入节点时,我的程序崩溃了.有什么提示吗?

But when I try to insert a node, my program crashes. Any hints what's the problem?

推荐答案

正如其他人所说,修改作为参数的指针不会对方法产生任何影响.

As other people have said, modifying a pointer that was a parameter won't have any effect outside of the method.

C通过值而不是通过引用传递指针.意味着您在函数中使用的指针是一个不同的指针,它仅指向同一事物.您必须将指针传递给像我上面的答案这样的指针.

C passes pointers by value not by reference. Meaning the pointer you're dealing with in the function is a different pointer that just points to the same thing. You have to pass a pointer to a pointer like the answer above me.

我希望我能评论一下这个解释,但我想我需要信誉才能做到这一点.

I wish I could've just commented this explanation but I guess I need reputation to do that..

这篇关于插入二叉搜索树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆