数据结构与算法:二叉搜索树的操作集
二叉搜索树是一种特殊的树结构,它能够将数据有序的储存起来,在进行查找时速度非常快,利用的是二分查找的思想,算法复杂度是O(logN),所以是一种非常重要的数据结构。
操作集包括:
按值查找节点,查找最小值节点,查找最大值节点,插入节点,删除节点。
其中最麻烦的是删除节点,在删除的函数里有详细的注释。
#include<cstdlib>
#include<stdio.h>
typedef struct TreeNode* BinTree;
struct TreeNode //定义
{
int data;
BinTree left;
BinTree right;
};
//查找递归实现
BinTree Find(int x, BinTree BST)
{
if(!BST) return 0;
if(BST->data == x) return BST;
else if(BST->data > x) return Find(x, BST->left);
else return Find(x, BST->right);
}
//查找迭代实现
BinTree iterFind(int x, BinTree BST)
{
while(BST)
{
if(x == BST->data) {return BST;}
else if(x > BST->data) {BST = BST->right;}
else {BST = BST->left;}
}
return BST;
}
//最小值
BinTree FindMin(BinTree BST)
{
if(!BST) return 0;
while(BST->left) {BST = BST->left;}
return BST;
}
//最大值
BinTree FindMax(BinTree BST)
{
if(!BST) return 0;
while(BST->left) {BST = BST->left;}
return BST;
}
//插入节点
BinTree Insert(int x, BinTree BST)
{
if(!BST)
{
BST = new TreeNode;
BST->left = 0; BST->right = 0;
BST->data = x;
return BST;
}
if(x > BST->data) {BST->right = Insert(x, BST->right);}
else if(x < BST->data) {BST->left = Insert(x, BST->left);}
return BST; //最后一层递归返回的是根节点
}
//删除节点
BinTree Delete(int x, BinTree BST)
{
BinTree p;
//先寻找目标节点
if(!BST) printf("not found");
else if(x > BST->data) BST->right = Delete(x, BST->right);
else if(x < BST->data) BST->left = Delete(x, BST->left);
//找到节点
else {
//两边节点都不为空,将右子树的最小值或左子树的最大值给本节点
if(BST->left&&BST->right){
p = FindMin(BST->right);
BST->data = p->data;
BST->right = Delete(p->data, BST->right);
}
//两边节点都为空或者只有一个为空的情况
else{
p = BST;
if(!BST->left) BST = BST->right;
else if(!BST->right) BST = BST->right;
free(p);
}
}
return BST;
}