2016-10-03 70 views
-1

我正在为我的家庭作业二叉搜索树,但它没有显示序为任何输出,后序。尽管我在inorderpreorderpostorder函数中使用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; 
} 
+0

_不给任何输出_。这是一个非常模糊的陈述。你在编译时是否收到错误?你用什么IDE来编译这个? –

回答

1

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未定义”消息可能会变得更加混乱。

而且由于没有解释如何解决这个问题使我是个任性的混蛋是谁的就在这里嘲讽“德noobz,”在这里失去了*r

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

,并宣布

node * r; 

main的顶部。在main的末尾,我强烈建议迭代所有节点的BST和delete以防止内存泄漏。我足够虐待一个虐待狂,不解释这一点。

+0

@ShaantamAnand阅读描述如何使用本网站的[** help tour **](https://stackoverflow.com/tour)。正确的答案可以通过正确答案和答案选择来记录,而你所做的都不是。如果你仍然没有给出应有的信用,人们会停止回答你的问题。 – WhozCraig