二进制搜索树:无输出

时间:2016-10-03 04:27:50

标签: c++ binary-search-tree

我正在为我的作业制作一个二元搜索树,但它没有显示 inorder 预订 postorder 的任何输出。即使我在cout inorderpreorder函数中使用了postorder,但它并没有给我任何输出。我感觉错误在于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;
}

1 个答案:

答案 0 :(得分:1)

createBst(r, val);

由于

中的自动变量r,OP尚未收到更新的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作为自动变量。一个拼写错误和一个干净的“变量未定义”消息可能会变得更加混乱。

因为没有解释如何解决这个让我成为一个自负的混蛋谁只是在这里嘲笑“teh noobz”,在这里失去了*r

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

并声明

node * r;

位于main的顶部。在main结束时,我强烈建议迭代BST并delete所有节点以防止内存泄漏。我已经足够成为虐待狂的折磨者,不能解释那个。

相关问题