数据结构与算法:二叉搜索树的操作集

数据结构与算法:二叉搜索树的操作集

二叉搜索树是一种特殊的树结构,它能够将数据有序的储存起来,在进行查找时速度非常快,利用的是二分查找的思想,算法复杂度是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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值