#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链接放出来 提交地址