加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 二叉搜索树(BST)

发布时间:2020-12-16 09:41:23 所属栏目:百科 来源:网络整理
导读:大家好,我犯了逻辑错误,但我没有发现错误. 谢谢 :)) 我的算法 #include iostream //iostreamusing namespace std;struct node{ struct node *left; struct node *right; int data;};void add(node *p,int sayi){ if(p==NULL){ p=new node(); p-data=sayi; p
大家好,我犯了逻辑错误,但我没有发现错误.

谢谢 :))

我的算法

#include <iostream>   //iostream

using namespace std;

struct node{

    struct node *left;
    struct node *right;
    int data;
};


void add(node *p,int sayi){

    if(p==NULL){
        p=new node();
        p->data=sayi;
        p->left=NULL;
        p->right=NULL;

    }
    else if(p->data>=sayi){
            add(p->left,sayi);  
    }
    else    {
            add(p->right,sayi);
    }

}

void postorder(node *p)
{

if(p!=NULL)

    {
        if(p->left!=NULL)
            postorder(p->left);
        if(p->right!=NULL)
            postorder(p->right);
        cout<< p->data<<endl;
    }
    else{
        cout<<"hata"<<endl;

    }
}

  void main(){

    struct node *k=NULL ;
    int sayi=0;

    while(sayi!=-1){
    cout<<"Bir sayi giriniz...";
    cin>>sayi;
    add(k,sayi);
    }
    postorder(k);

    system("pause");
}

解决方法

您按值传递struct node * k.无论何时在函数中更改它(如添加),它只会更改本地副本(在函数中),因此您将返回NULL指针.通过引用或指针传递它:

void add(node* &p,int sayi)
{
     ...
}

struct node *k = 0;
...
add(k);

要么

void add(node** p,int sayi)
{
     ... 
}

struct node *k = 0;
...
add(&k);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读