c++ - 二叉搜索树(BST)

标签 c++ tree binary-search-tree

<分区>

大家好,我犯了逻辑错误,但我没有发现错误。

谢谢你:))

我的算法

#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。每当您在函数中更改它(如在 add 中)时,它只会更改本地拷贝(在函数中),因此您会得到一个 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);

关于c++ - 二叉搜索树(BST),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14012173/

相关文章:

c++ - 使用 Boost::Spirit 从中缀到前缀的 n 元 bool 语法转换?

c++:交换 map 的 map

algorithm - 这是我为硬币找零挑战找到的正确递归关系吗?

c - 最优二叉树搜索

java - 在 Java 中测试两个 BST 是否相等

c++ - postblit 构造函数与复制构造函数仅在源上有所不同吗?

javascript - Javascript 中的树结构

python - "nicely"如何打印出一棵没有节点信息的树

c - 在循环中使用 scanf() 扫描 CSV 文件在第一行和第二行开始后停止

c++ - std::map 和性能,相交集