#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define KeyType int
//构建结点
typedef struct BiTreeNode{
KeyType data;//结点内的数据
BiTreeNode *lchild;//左孩子结点
BiTreeNode *rchild;//右孩子结点
}BiTNode,*BiTree;//指向BiNode类型的指针变量BiTree
void Show(BiTree T){
if(T){
Show(T->lchild);
printf("%d ",T->data);
Show(T->rchild);
}
}
void CreatBST(BiTree &T){
T = NULL;
}
bool BST(BiTree &T,KeyType key){
while(T){
if(key == T->data){
printf("已在排序内找到 %d",key);
return true;
}
else if(key > T->data) T = T->rchild;
else T= T->lchild;
}
printf("未在排序内找到 %d",key);
return false;
}
int InsertKey(BiTree &T,KeyType x){
if(!T){
T = (BiTree)malloc(sizeof(BiTNode));
T->data = x;
T->lchild = T->rchild = NULL;
return 1;
}
if(x == T->data) return 0;
else if(x > T->data) return InsertKey(T->rchild,x);
else return InsertKey(T->lchild,x);
}
int main(){
BiTree T;//T表示根节点
CreatBST(T);
InsertKey(T,51);
InsertKey(T,28);
InsertKey(T,81);
InsertKey(T,7);
InsertKey(T,9);
Show(T);
printf("\n");
BST(T,9);
return 0;
}
数据结构——排序 二叉排序树(C语言实现)
于 2023-12-08 16:26:29 首次发布