二叉搜索树:无输出

Binary Search Tree : no output

本文关键字:输出 搜索树      更新时间:2023-10-16

我正在为我的作业做一个二叉搜索树,但它没有显示inorderpreorder poststor 的任何输出。即使我在inorder preorderpostorder函数中使用cout,但它没有给我任何输出。我觉得错误是在createBst功能,但我不确定…请帮帮我吧提前谢谢你:-)

#include <iostream>
using namespace std;
struct node
{
    int info;
    struct node *left;
    struct node *right;
}*r;
struct node * createBst(struct node *r, int val)
{
    if (r == NULL)
    {
        r = new node;
        r->info = val;
        r->left = NULL;
        r->right = NULL;
    }
    else if (val <= r->info)
    {
        // cout<<r->left<<" ";
        r->left = createBst(r->left, val);
    }
    else
    {
        r->right = createBst(r->right, val);
        cout << r->right << " ";
    }
    return r;
}
void inOrder(struct node *r)
{
    if (r != NULL)
    {
        inOrder(r->left);
        cout << r->info;
        inOrder(r->right);
    }
}
void preOrder(struct node *r)
{
    if (r != NULL)
    {
        cout << r->info;
        preOrder(r->left);
        preOrder(r->right);
    }
}
void postOrder(struct node *r)
{
    if (r != NULL)
    {
        postOrder(r->left);
        postOrder(r->right);
        cout << r->info;
    }
}
int main()
{
    r = NULL;
    int n, val;
    cout << "Enter the number of element" << endl;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> val;
        //cout<<"check";
        createBst(r, val);
    }
    cout << "Inorder" << endl;
    //cout<<r->info<<endl;
    inOrder(r);
    cout << endl;
    cout << "PreOrder" << endl;
    preOrder(r);
    cout << endl;
    cout << "PostOrder" << endl;
    postOrder(r);
    cout << endl;
}

In

createBst(r, val);

OP没有收到更新后的r,因为

中的自动变量r
struct node * createBst(struct node *r, int val)

不是同一个r
struct node
{
    int info;
    struct node *left;
    struct node *right;
}*r;

可以使用

修复
r = createBst(r, val);

或通过更改

struct node * createBst(struct node *r, int val)

通过引用获取指针。

struct node * createBst(struct node * & r, int val)

离题了,OP设置了一些可笑的编译器和逻辑错误,将r作为全局变量,然后在其函数中广泛使用变量名称r作为自动变量。一个错别字加上一个清晰的"变量r未定义"消息会让整个过程变得更加混乱。

因为不解释如何解决这个问题使我成为一个自私的混蛋,只是在这里嘲笑"the noobz",在这里失去*r:

struct node
{
    int info;
    struct node *left;
    struct node *right;
}*r;

和声明

node * r;

main的顶部。在main结束时,我强烈建议遍历BST和delete所有节点,以防止内存泄漏。我是一个虐待成性的折磨者,所以我不解释这个。