二叉搜索树的查找,删除,插入-C语言代码
1. 什么是二叉搜索树?
2. 基本操作
2.1 存储结构
#include <stdio.h>
#include<stdlib.h>
#define ElementType int
typedef struct TreeNode
{
ElementType data;
TreeNode* lchild;
TreeNode* rchild;
}BinSearchTree;
2.2 建树(前序遍历建树)
void CreateTree(BinSearchTree** root)//前序遍历
{
ElementType ch;
scanf("%d\n",&ch);
//ch=getchar();
if (ch==-1){
*root=NULL;
}
else{
(*root)=(BinSearchTree*)malloc(sizeof(TreeNode));
(*root)->data=ch;
CreateTree(&((*root)->lchild));
CreateTree(&((*root)->rchild));
}
}
2.3 查找某个元素(迭代查找,非递归)
BinSearchTree* IterFind(BinSearchTree* root,ElementType x)
{
while(root){
if(x>root->data){
root=root->rchild;
}
else if(x<root->data){
root=root->lchild;
}
else{
return root;
}
}
return NULL;
}
2.4 查找最大元素
最右边的元素是最大的
BinSearchTree* FindMax(BinSearchTree* root)
{
while(root->rchild){
root=root->rchild;
}
return root;
}
2.5 查找最小元素
最右边的元素是最小的
BinSearchTree* FindMin (BinSearchTree* root)
{
while(root->lchild){
root=root->lchild;
}
return root;
}
2.6 插入一个元素
BinSearchTree* Insert(BinSearchTree* root,int x)
{
if(!root){
root=(BinSearchTree*)malloc(sizeof(TreeNode));
root->data=x;
root->lchild=root->rchild=NULL;
}
else
if(x>root->data){
root->rchild=Insert(root->rchild,x);
}else if(x<root->data){
root->lchild=Insert(root->lchild,x);
}
return root;
}
2.7 删除一个元素
BinSearchTree* Delete(BinSearchTree* root,int x)
{
BinSearchTree* tmp;
if(!root){
printf("未找到!");
}
else{
if(x>root->data){
root->rchild=Delete(root->rchild,x);
}else if(x<root->data){
root->lchild=Delete(root->lchild,x);
}else{
if(root->lchild && root->rchild){
tmp=FindMin(root->rchild);
root->data=tmp->data;
root->rchild=Delete(root->rchild,root->data);
}else{
tmp=root;
if(!root->lchild){
root=root->rchild;
}
else{
root=root->lchild;
}
free(tmp);
}
}
}
return root;
}
2.8 输出树
void PrintTree(BinSearchTree* root,int h)
{
if(root==NULL) return;
else{
PrintTree(root->rchild,h+1);
for(int i=0;i<h;i++) printf("\t");
printf("%d\n",root->data);
PrintTree(root->lchild,h+1);
}
}