问题:
问题链接:点击打开链接
题目1201:二叉排序树
分析:
简单的二叉排序树的操作。
代码:
#include <iostream>
#include <malloc.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Node{
int data;
Node * lchild,*rchild;
};
typedef struct Node * Tree;
void init_Tree(Tree t){
t = (Node *) malloc(sizeof(Node));
t->lchild=t->rchild = NULL;
}
void insert_T(Tree &t,int x){
//将结点x插入到二叉排序树t中
if(t == NULL){
Node *n = (Node *)malloc(sizeof(Node));
n->data = x;
n->lchild = n->rchild =NULL;
t = n;
} else{
if(x>t->data){
insert_T(t->rchild,x);
}else{
insert_T(t->lchild,x);
}
}
}
void frontTra(Tree t){
//先序遍历
if(t!=NULL) {
printf("%d",t->data);
}
if(t->lchild!= NULL){
frontTra(t->lchild);
}
if(t->rchild!= NULL){
frontTra(t->rchild);
}
}
void midTra(Tree t){
//中序遍历
if(t->lchild!= NULL){
midTra(t->lchild);
}
if(t!=NULL) {
printf("%d",t->data);
}
if(t->rchild!= NULL){
midTra(t->rchild);
}
}
void rearTra(Tree t){
//后序遍历
if(t->lchild!= NULL){
rearTra(t->lchild);
}
if(t->rchild!= NULL){
rearTra(t->rchild);
}
if(t!=NULL) {
printf("%d",t->data);
}
}
int main(int argc, char** argv) {
int n;
while(scanf("%d",&n)!= EOF){
Tree t;
//init_Tree(t);
while(n--){
int tmp;
scanf("%d",&tmp);
insert_T(t,tmp);
}
frontTra(t);
printf("\n");
midTra(t);
printf("\n");
rearTra(t);
free(t);
}
return 0;
}