weixin_42703390 2019-02-03 20:20 采纳率: 100%
浏览 623

C++ 写了一个二叉排序树的小程序,在牛客网OJ报错,请教一下各位。

#include <iostream>
#include <stack>
#include <queue>
using namespace std;
struct Node{
    int data;
    Node *lchild;
    Node *rchild;
};
struct BST{
    Node *root;
    void insert(int x){
        if(root == NULL){
            root = new Node;
            root->rchild=root->lchild=NULL;
            root->data = x;
            return;
        }
        Node *tmp = root;
        while(tmp!=NULL){
            if(x<tmp->data){
                if(tmp->lchild!=NULL)
                    tmp = tmp->lchild;
                else{
                    tmp->lchild = new Node;
                    tmp->lchild->rchild=tmp->lchild->lchild=NULL;
                    tmp->lchild->data = x;
                    return;
                }
            }else if(x>tmp->data){
                if(tmp->rchild!=NULL)
                    tmp = tmp->rchild;
                else{
                    tmp->rchild = new Node;
                    tmp->rchild->rchild=tmp->rchild->lchild=NULL;
                    tmp->rchild->data = x;
                    return;
                }
            }
            else    return;
        }   
    }
    void PreOrder(){
        if(root == NULL)    return;
        Node *tmp=root;
        stack <Node*> s;
        while(tmp!=NULL||!s.empty()){
            if(tmp!=NULL){
                printf("%d ",tmp->data);
                s.push(tmp);
                tmp = tmp->lchild;
            }
            else{
                tmp = s.top();
                s.pop();
                tmp = tmp->rchild;
            }
        }
    }
    void InOrder(){
        if(root == NULL)    return;
        Node *tmp = root;
        stack <Node*> s;
        while(tmp!=NULL||!s.empty()){
            if(tmp!=NULL){
                s.push(tmp);
                tmp = tmp->lchild;
            }
            else{
                tmp = s.top();
                s.pop();
                printf("%d ",tmp->data);
                tmp = tmp->rchild;
            }
        }
    }
};
void PostOrder(Node *root){
    if(root==NULL)  return;
    PostOrder(root->lchild);
    PostOrder(root->rchild);
    cout<<root->data<<' ';
}
int main(){
    int n;
    BST b;
    cin>>n;
    while(n--){
        int tmp;
        cin>>tmp;
        b.insert(tmp);
    }   
    b.PreOrder();
    cout<<endl;
    b.InOrder();
    cout<<endl;
    PostOrder(b.root);
    cout<<endl;
}

提示如下:
段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起。
小弟百度了很久,实在不知道怎么办了,我本地运行都正常呢,OJ就是不通过。
我把oj链接放出来 提交地址

  • 写回答

1条回答 默认 最新

  • devmiao 2019-02-06 22:31
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog