BST(二叉排序树)的创建和使用

#include <stdio.h>
#include <stdlib.h>
typedef struct node_1{
int value;
struct node_1 *left_child;
struct node_1 *right_child;
}BinaryTree;


void insert_node(BinaryTree **p,int e){
BinaryTree *temp=NULL;
temp=(BinaryTree*)malloc(sizeof(BinaryTree));
temp->value=e;
temp->left_child=NULL;
temp->right_child=NULL;
if(*p==NULL) {
*p=temp;
return;
}
BinaryTree *bj=NULL;
bj=*p;
while(bj){
if(bj->value<e){
if(bj->right_child==NULL){
bj->right_child=temp;
return ;
}
bj=bj->right_child;
}
else if(bj->value>e){
if(bj->left_child==NULL){
bj->left_child=temp;
return;
}
bj=bj->left_child;
}
else{
printf("error\n");
free(temp);
temp=NULL;
return;
}
}
}


void create(BinaryTree **b,int a[],int len){
if(a==NULL || len<=0)  return ;
int i;
for(i=0;i<len;i++){
insert_node(b,a[i]);
}
}


void Pre_BinaryTree(BinaryTree *b){
if(b==NULL)  return ;
printf("%d ",b->value);
Pre_BinaryTree(b->left_child);
Pre_BinaryTree(b->right_child);
}


int main(){
int a[]={11,22,55,6,3,66,8};
BinaryTree *b=NULL;
create(&b,a,sizeof(a)/sizeof(a[0]));
Pre_BinaryTree(b);
return 0;
}



猜你喜欢

转载自blog.csdn.net/qq_42211587/article/details/80950521