创建二叉排序树,先序遍历,中序遍历,判断是否存在关键点
这是所要创建的二叉排序树,a[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8},请先在草稿纸上画出图形,再看程序
代码实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct BTNode{
int key,cout;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
//创建二叉排序树
bool BSTInsert(BTNode *&bt,int x){
if(bt==NULL){
bt=(BTNode*)malloc(sizeof(BTNode));
bt->key=x;
bt->lchild=bt->rchild=NULL;
return true;
}
if(x==bt->key)
return false;
if(x>bt->key)
return BSTInsert(bt->rchild,x);
else
return BSTInsert(bt->lchild,x);
}
//先序遍历
void PreOrderTraverse(BTNode *bt){
if(bt){
printf("%d ",bt->key);
PreOrderTraverse(bt->lchild);
PreOrderTraverse(bt->rchild);
}
}//中序遍历
void InOrderTraverse(BTNode *bt){
if(bt){
InOrderTraverse(bt->lchild);
printf("%d ",bt->key);
InOrderTraverse(bt->rchild);
}
}
//查找关键点是否存在
bool BSTSearch(BTNode *bt,int x){//找到关键字返回1,否则返回0
if(!bt){
return 0;
}
else{
if(bt->key==x)
return 1;
else if(bt->key>x)
return BSTSearch(bt->lchild,x);
else
return BSTSearch(bt->rchild,x);
}
}
int main(int argc, char *argv[])
{
int i,a[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8};
struct BTNode *bt=NULL;
for(i=0;i<10;++i){
BSTInsert(bt,a[i]);
}
printf("%d\n",BSTSearch(bt,6));
printf("先序遍历:");
PreOrderTraverse(bt);
printf("\n中序遍历:");
InOrderTraverse(bt);
printf("\n");
return 0;
}
输出结果:
1
先序遍历:4 2 1 0 3 5 9 7 6 8
中序遍历:0 1 2 3 4 5 6 7 8 9
请按任意键继续. . .