由{4,9,0,1,8,6,3,5,2,7}创建一个二叉排序树
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
#define ElemType int
typedef struct BSTNode{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
void BSTInsert(BSTree &T,ElemType key){
if(T==NULL){
T=(BSTree)malloc(sizeof(BSTNode));
T->data=key;
T->lchild=NULL;
T->rchild=NULL;
}
if(key==T->data){
}//判断树中是否存在相同关键字的节点
if(key<T->data){
BSTInsert(T->lchild,key);
}
if(key>T->data){
BSTInsert(T->rchild,key);
}
}//二叉排序树的插入
void CreatBST(BSTree &T,ElemType str[MAXSIZE],int n){
T=NULL;
for(int i=0;i<n;i++){
BSTInsert(T,str[i]);
}
}//创建二叉排序树
void visit(BSTree &T){
if(T!=NULL){
printf("%d ",T->data);
}
}
void InOrder(BSTree &T){
if(T){
InOrder(T->lchild);
visit(T);
InOrder(T->rchild);
}
}
int main(){
BSTree T;
ElemType str[MAXSIZE]={4,9,0,1,8,6,3,5,2,7};
CreatBST(T,str,10);
InOrder(T);
}