#include <stdio.h>
#include <stdlib.h>
typedef struct BSTNode{
int data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BiTree;
BSTNode *BST_Search1(BiTree T,int key){ //查找值为key的结点(while循环)
while(T!=NULL&&key!=T->data){
if(key<T->data){
T=T->lchild;
}
else{
T=T->rchild;
}
}
if(T==NULL){
printf("无值为%d的结点",key);
return NULL;
}
else{
return T;
}
}
BSTNode *BST_Search2(BiTree T,int key){//查找值为key的结点(递归)
if(T!=NULL){
if(key=T->data){
return T;
}
else if(key<T->data){
BST_Search2(T->lchild,key);
}
else if(key>T->data){
BST_Search2(T->rchild,key);
}
}
else{
printf("无值为%d的结点",key);
return NULL;
}
}
int BST_Insert(BiTree &T,int k){
if(T==NULL){ //树为空,创建一个结点作为根节点,跟结点的值为k
T=(BiTree)malloc(sizeof(BSTNode));
T->data=k;
T->lchild=NULL;
T->rchild=NULL;
return 1; //插入成功
}
else if(k==T->data){ //树中存在相同值的结点
return 0; //插入失败
}
else if(k<T->data){ //插入到左子树
BST_Insert(T->lchild,k);
}
else if(k>T->data){
BST_Insert(T->rchild,k);
}
}
void Creat_BST(BiTree &T,int str[],int n){//创建二叉排序树 ,n为str的长度
T=NULL; //初始为空树
int i=0;
while(i<n){
BST_Insert(T,str[i]);
i++;
}
}
int main(){
BiTree T;
int str[7]={4,2,3,1,5,6,7};
Creat_BST(T,str,7);
return 0;
}
版权声明:本文为qq_40280704原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。