下面代码是自己在学习二叉查找树时写的,纯属为了记录自己的学习过程。
//C语言实现二叉查找树
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct _SearchTreeNode{
struct _SearchTreeNode *left;
struct _SearchTreeNode *right;
int data;
}SearchTreeNode;
//往二叉查找树中插入元素
SearchTreeNode *Insert(SearchTreeNode *tree,int element){
if(tree==NULL){
tree=(SearchTreeNode*)malloc(sizeof(SearchTreeNode));
if(tree==NULL){
printf("error!");
return NULL;
}
else{
tree->data=element;
tree->left=tree->right=NULL;
}
}
else{
if(element<tree->data){
tree->left=Insert(tree->left,element);
}
else{
tree->right=Insert(tree->right,element);
}
}
return tree;
}
//查找最小值
SearchTreeNode *FindMin(SearchTreeNode *tree){
if(tree==NULL){
return NULL;
}
else{
if(tree->left!=NULL){
return FindMin(tree->left);
}
else{
return tree;
}
}
}
//查找最大值
SearchTreeNode *FindMax(SearchTreeNode *tree){
if(tree==NULL){
return NULL;
}
else{
if(tree->right==NULL){
return tree;
}
else{
return FindMax(tree->right);
}
}
}
//删除二叉查找树中某一元素element
//分以下几种情况:
// (1)删除的结点有两个孩子
//(2)删除的结点有一个孩子
//(3)删除的结点没有孩子
SearchTreeNode *Delete(SearchTreeNode *tree,int element){
SearchTreeNode *min_right;
if(tree==NULL){
return NULL;
}
else{
if(element==tree->data){
if(tree->right==NULL&&tree->left==NULL){
tree=NULL;
return tree;
}
else if(tree->right!=NULL&&tree->left==NULL){
tree=tree->right;
}
else if(tree->left!=NULL&&tree->right==NULL){
tree=tree->left;
}
else{
min_right=FindMin(tree->right);
tree->data=min_right->data;
tree->right=Delete(tree->right,tree->data);
}
}
else if(element<tree->data){
tree->left=Delete(tree->left,element);
}
else{
tree->right=Delete(tree->right,element);
}
}
return tree;
}
//查找二叉查找树中的某一元素
SearchTreeNode *Find(SearchTreeNode *tree,int element){
if(tree==NULL){
return NULL;
}
else{
if(element==tree->data){
return tree;
}
else if(element<tree->data){
return Find(tree->left,element);
}
else{
return Find(tree->right,element);
}
}
}
//先序遍历
void PreOrder(SearchTreeNode *tree){
if(tree!=NULL){
printf(" %d ",tree->data);
PreOrder(tree->left);
PreOrder(tree->right);
}
}
//中序遍历
void InOrder(SearchTreeNode *tree){
if(tree!=NULL){
InOrder(tree->left);
printf(" %d ",tree->data);
InOrder(tree->right);
}
}
int main(int argc, char *argv[]) {
SearchTreeNode *tree=NULL,*min,*max,*ele;
tree=Insert(tree,6);
tree=Insert(tree,2);
tree=Insert(tree,1);
tree=Insert(tree,5);
tree=Insert(tree,3);
tree=Insert(tree,4);
tree=Insert(tree,8);
tree=Delete(tree,6);
PreOrder(tree);
printf("\n");
InOrder(tree);
printf("\n");
min=FindMin(tree);
printf("the min data of tree is : %d\n",min->data);
max=FindMax(tree);
printf("the max data of tree is: %d\n",max->data);
ele=Find(tree,1);
printf("%d",ele->data);
return 0;
}