//@author:hairu,wu
#include<iostream>
using namespace std;
struct Tree{
int data;
Tree *lchild,*rchild;
};
void Insert(Tree* &tree,int x){
if(tree==NULL){
tree = new Tree();
tree->data=x;
tree->lchild=tree->rchild=NULL;
}else{
if(x< tree->data){
Insert(tree->lchild,x);
}else{
Insert(tree->rchild,x);
}
}
}
//先序遍历
void preOrder(Tree *t){
if(t!=NULL){
cout<<t->data<<" ";
}
if(t->lchild!=NULL){
preOrder(t->lchild);
}
if(t->rchild!=NULL){
preOrder(t->rchild);
}
}
//中序遍历
void inOrder(Tree *t){
if(t->lchild!=NULL){
inOrder(t->lchild);
}
if(t!=NULL){
cout<<t->data<<" ";
}
if(t->rchild!=NULL){
inOrder(t->rchild);
}
}
//后序遍历
void lastOrder(Tree *t){
if(t->lchild!=NULL){
lastOrder(t->lchild);
}
if(t->rchild!=NULL){
lastOrder(t->rchild);
}
if(t!=NULL){
cout<<t->data<<" ";
}
}
int main(){
int n;
cin >> n;
Tree *tree=NULL; //千万要写=NULL
for(int i=0;i<n;i++){
int x;
cin >> x;
Insert(tree,x);
}
//先序遍历
preOrder(tree);
cout<<endl;
inOrder(tree);
cout<<endl;
lastOrder(tree);
return 0;
}
BST的C++实现
最新推荐文章于 2024-05-13 21:13:38 发布