weixin_42703390
2019-02-03 20:20C++ 写了一个二叉排序树的小程序,在牛客网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条回答
为你推荐
- C++练习题:共需多少钱?
- c++
- 2个回答
- C++OJ题 数字归类 求解
- c++
- 1个回答
- 求教本机编译通过oj上却显示编译错误的原因?
- c++
- 2个回答
- 在牛客网oj上的一道题,本地测试正确,在网上怎么也不对,求解答(北理研究生复试题,学生查询问题)
- c语言
- c++
- 3个回答
- 写北大oj1003时的疑惑,求各位路过的大佬帮帮忙
- c语言
- 1个回答
换一换