C语言实现二叉搜索树

130 阅读1分钟

 

二叉搜索树

1.定义

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

2.搜索

Position Find(BinTree BST, ElementType X) {
    if (!BST) {//未找到
        return NULL;
    }
    else if (BST->Data > X) {//左递归查找
        return Find(BST->Left, X);
    }
    else if (BST->Data < X) {//右递归查找
        return Find(BST->Right, X);
    }
    else {//找到了
        return BST;
    }
}

3.插入

BinTree Insert(BinTree BST, ElementType X) {
    if (!BST) {//找到了要插入的叶子节点
        BST = (BinTree)malloc(sizeof(struct TNode));
        BST->Data = X;
        BST->Left = NULL;
        BST->Right = NULL;
    }
    else if (BST->Data > X) {//右递归插入
        BST->Left = Insert(BST->Left, X);
    }
    else if (BST->Data < X) {//左递归插入
        BST->Right = Insert(BST->Right, X);
    }
    return BST;
}

3.按照str[]中的关键字序列建立二叉排序树(待修改,勿用)

void Creat_void(BSTree& T, int str[], int n) {
    T = NULL;
    int i = 0;
    while (i < n) {
        BST_Insert(T, str[i]);
        i++;
    }
}

4.最小元素

Position FindMin(BinTree BST)
{
    if (!BST)//传入的是一棵空树
    {
        return NULL;
    }
    else if (BST->Left != NULL) {
        return FindMin(BST->Left);//一直向左查找
    }
    else {
        return BST;
    }
}
​

5.最大元素

Position FindMax(BinTree BST)
{
    if (!BST) {//传入的是一颗空树
        return NULL;
    }
    else if (BST->Right != NULL) {
        return FindMax(BST->Right);//一直向右查找
    }
    else {
        return BST;
    }
}

6.删除

BinTree Delete(BinTree BST, ElementType X) {
    if (!BST) {//到了叶子节点也没有找到
        printf("Not Found\n");
    }
    else if (BST->Data > X) {
        BST->Left = Delete(BST->Left, X);//左递归查找
    }
    else if (BST->Data < X) {
        BST->Right = Delete(BST->Right, X);//右递归查找
    }
    else if (BST->Left != NULL && BST->Right == NULL) {//只有左子树
        BinTree tmp = BST;
        BST = BST->Left;
        free(tmp);
    }
    else if (BST->Left == NULL && BST->Right != NULL) {//只有右子树
        BinTree tmp = BST;
        BST = BST->Right;
        free(tmp);
    }
    else if (BST->Left == NULL && BST->Right == NULL) {//无子树
        free(BST);
        BST = NULL;
    }
    else {//左右子树都不空
        Position tmp = FindMin(BST->Right);//在右子树中找最小值
        BST->Data = tmp->Data;
        BST->Right = Delete(BST->Right, BST->Data);//s
    }
    return BST;
}