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 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?