数据结构学习第7篇 - 二叉搜索树

本文详细介绍了二叉搜索树的概念,并提供了用C语言实现二叉搜索树的基本操作,包括初始化、销毁、插入、查找、删除和遍历(前序和中序)。通过示例代码展示了如何进行增删改查以及遍历操作,便于理解和实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉搜索树

二叉搜索树是二叉树的重要应用。请编写实现二叉搜索树的基本操作,主要包括:初始化(得到空二叉搜索树)、销毁(释放二叉搜索树的所有节点)、插入、查找(迭代和递归实现)、删除和遍历(前序和中序,分别迭代和递归实现)。

注意:1.树中的元素可以是简单类型,如int类型

      2.通过不断插入元素可以得到二叉搜索树


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/**********************类型定义 ********************/
#define MAXNODE 200

typedef int elemtype;
 
typedef struct node
{
    elemtype data;  
    struct node *lchild,*rchild;
} BSNode, *BSTree;

BSTree init();                                                //初始化
void destroy(BSTree bst);                                    //注销
BSTree search(BSTree bst,elemtype x);                        //递归搜索
int insert(BSTree *bst,elemtype x);                            //插入
BSTree del(BSTree bst,elemtype x);                            //删除
void NRPreOrder(BSTree bst);                                //迭代先序遍历
void PreOrder(BSTree bst);                                    //递归先序遍历
void InOrder(BSTree bst);                                    //递归中序遍历
void NRInOrder(BSTree bst);                                    //迭代中序遍历
BSTree NRsearch(BSTree bst,elemtype x);                     //迭代搜索
void Menu(void);                                            //主菜单

elemtype x[MAXNODE];                                        //存放各节点数据的数组

 

int main()
{
    BSTree bst = NULL;
    int i,n,op;
    elemtype X;
    while(1)
    {
        Menu();
        scanf("%d",&op);
        switch(op)
        {
            case 1:
                printf("请输入你要输入的数字个数:");
                scanf("%d",&n);
                for(i = 0; i < n; i++)
                {
                    scanf("%d",&x[i]);
                    if(i == 0)
                    {
                        bst = init();
                        bst->data = x[i];
                    }
                    else
                    {
                        insert(&bst, x[i]);
                    }
                }
                break;
                
            case 2:
                printf("请输入你要删除的数字:\n");
                scanf("%d",&X);
                del(bst,X);
                break;
                
            case 3:
                printf("请输入你想查找的数字:\n");
                scanf("%d",&X);
                printf("递归查找:\n");
                search(bst, X);
                printf("迭代查找:\n");
                NRsearch(bst, X);
                break;
                
            case 4:
                printf("递归前序遍历: \n");
                PreOrder(bst);
                printf("迭代前序遍历:\n");
                NRPreOrder(bst);
                printf("递归中序遍历:\n");
                InOrder(bst);
                printf("迭代中序遍历:\n");
                NRInOrder(bst);
                break;
                
            case 5:
                printf("菜单已退出!\n");
                return 0;
        }
    }
}

//主菜单
void Menu(void)
{
    printf("功能菜单:\n");
    printf("\t1.创建二叉搜索树\n");
    printf("\t2.删除二叉搜索树\n");
    printf("\t3.搜索二叉搜索树\n");
    printf("\t4.遍历二叉搜索树\n");
    printf("\t5.注销并推出菜单\n");
    printf("请输入你的选择:\n");
}


//初始化搜索二叉树
BSTree init(void)
{
    BSTree root = (BSTree)malloc(sizeof(BSNode));
    root->lchild = NULL;
    root->rchild = NULL;
    return root;
}

//插入
int insert(BSTree* bst,elemtype x)
{
    int i;
    
    if(*bst == NULL)
    {
        *bst =(BSTree)malloc(sizeof(BSNode));
        if(*bst == NULL)
        {
            printf("动态内存没有分配!\n");    
        }    
        else
        {
            (*bst)->data = x;
            //printf("%d\n",p->data);
            (*bst)->lchild = NULL;
            (*bst)->rchild = NULL;
        }
    }
    else
    {
        if(x < (*bst)->data)
        {
            printf("左\n");
            insert(&(*bst)->lchild, x);    
        }
        else
        {
            if(x > (*bst)->data)
            {
                printf("右\n");
                insert(&(*bst)->rchild, x);    
            }    
        }    
    }
}

//递归搜素
BSTree search(BSTree bst,elemtype x)
{
    if(bst == NULL)
    {
        printf("查无此人!\n");
        return NULL;
    }
    else
    {
        if(x < bst->data)
        {
            search(bst->lchild, x);
        }    
        else
        {
            if(x > bst->data)
            {
                search(bst->rchild, x);
            }
            else
            {    
                printf("查有此人!\n");
                printf("%d\n",bst->data);
                return bst;    
            }
        }
    }
}

//迭代搜索
BSTree NRsearch(BSTree bst,elemtype x)
{
    while(bst!=NULL)
    {
        if(x < bst->data)
        {
            bst = bst->lchild;
        }
        else if(x > bst->data)
        {
            bst = bst->rchild;
        }
        else if(x == bst->data)
        {
            printf("查有此人!\n");
            printf("%d\n",bst->data);
            return bst;
        }
    }
    if(bst == NULL)
    {
        printf("查无此人!\n");
        return NULL;
    
    }    
}

//找该子树最小权重节点
BSTree FindMin(BSTree bst)
{
    if(bst == NULL)
    {
        return NULL;
    }
    else
    {
        if(bst->lchild == NULL)
        {
            return bst;
        }
        else
        {
            return FindMin(bst->lchild);    
        }    
    }
}

BSTree TmpCell;                                                //删除节点的指针

//递归删除
BSTree del(BSTree bst,elemtype x)
{
    if(bst == NULL)
    {
        printf("查无此人!删除失败!\n");
    }
    else
    {
        if(x < bst->data)
        {
            bst->lchild = del(bst->lchild, x);
        }
        else
        {
            if(x > bst->data)
            {
                bst->rchild = del(bst->rchild, x);
            }    
            else
            {
                if(bst->lchild != NULL && bst->rchild != NULL)
                {
                    TmpCell = FindMin(bst->rchild);
                    bst->data = TmpCell->data;
                    bst->rchild = del(bst->rchild, bst->data);
                }    
                else
                {
                    TmpCell = bst;
                    if(bst->lchild == NULL)
                    {
                        bst = bst->rchild;
                    }    
                    else
                    {
                        if(bst->rchild == NULL)
                        {
                            bst = bst->lchild;
                        }
                    }
                    free(TmpCell);
                }
            }
        }
    }
    return bst;
}

//注销
void destory(BSTree bst)
{
    if(bst != NULL)
    {
        destory(bst->lchild);
        destory(bst->rchild);
        free(bst);    
    }
    return;
}

//查看
void Visite(elemtype p)
{
    printf("%d\n",p);
    
    return;
}

//递归先序遍历
void PreOrder(BSTree bst)
{

    BSTree p = bst;
    if(p == NULL)
    {
        return;
    }
    Visite(p->data);
    
    PreOrder(p->lchild);
    PreOrder(p->rchild);
}

//迭代先序遍历
void NRPreOrder(BSTree bst)
{

    BSTree p = bst;
    if(p == NULL)
    {
        return;
    }

    BSTree stack[MAXNODE];
    
    int top = 0;

    while(!(p == NULL && top == 0))
    {
        
        while(p !=    NULL)
        {
            
            Visite(p->data);
            
            if(top < MAXNODE - 1)
            {
                stack[top] = p;
                top++;
            }
            else
            {
                printf("栈溢出!\n");
                return;
            }
            p = p->lchild;
        }
        top--;
        p = stack[top];
        p = p->rchild;
    
    }
    return;
}

//递归中序遍历
void InOrder(BSTree bst)
{
    if(bst == NULL)
    {
        return;
    }
    else
    {
        InOrder(bst->lchild);
        Visite(bst->data);
        InOrder(bst->rchild);
    }
}

//迭代中序遍历
void NRInOrder(BSTree bst)
{

    BSTree p = bst;
    if(p == NULL)
    {
        return;
    }

    BSTree stack[MAXNODE];
    
    int top = 0;

    while(!(p == NULL && top == 0))
    {
        
        while(p !=    NULL)
        {
            
            
            
            if(top < MAXNODE - 1)
            {
                stack[top] = p;
                top++;
            }
            else
            {
                printf("栈溢出!\n");
                return;
            }
            p = p->lchild;
        }
        top--;
        p = stack[top];
        Visite(p->data);
        p = p->rchild;
    
    }
    return;
}

 

### PTA 7-2 二叉搜索树结构实现与问题解决方案 #### 描述 在处理PTA平台上有关二叉搜索树BST)的问题时,理解其基本操作至关重要。这不仅涉及创建和维护一棵平衡的二叉搜索树,还包括执行诸如插入、删除以及查询等常见任务。 #### 创建二叉搜索树 为了构建一个有效的二叉搜索树,在初始化阶段应当首先定义好节点的数据结构,并确保每次新增元素都能按照左子树小于父节点而右子树大于等于父节点的原则正确放置[^3]。 ```cpp struct TreeNode { int val; TreeNode *left, *right; TreeNode(int x) : val(x), left(NULL), right(NULL){} }; ``` 当向已存在的二叉搜索树中添加新值时,可以通过递归方式来完成: ```cpp TreeNode* insertIntoBST(TreeNode* root, int val){ if (!root) return new TreeNode(val); if (val < root->val) root->left = insertIntoBST(root->left, val); else root->right = insertIntoBST(root->right, val); return root; } ``` #### 删除特定数值对应的节点 对于删除操作而言,存在三种可能的情形:目标节点无任何孩子;只有一个孩子;有两个孩子。前两种情形相对容易处理——只需调整指针指向即可解决问题。然而第三种情况则较为复杂一些,通常的做法是从右侧寻找最小值作为替代品并移除之[^4]。 ```cpp TreeNode* deleteNode(TreeNode* root, int key){ if(!root) return nullptr; if(key < root->val) root->left = deleteNode(root->left, key); else if(key > root->val) root->right = deleteNode(root->right, key); else{ // Node with only one child or no child if(!root->left || !root->right){ TreeNode* temp = root->left ? root->left : root->right; if(temp == NULL){ // No children case temp = root; root = NULL; }else{ // One child case *root = *temp; } free(temp); }else { // Two children cases TreeNode* minNodeOnRightSubtree = findMin(root->right); root->val = minNodeOnRightSubtree->val; root->right = deleteNode(root->right,minNodeOnRightSubtree->val); } } return root; } // Helper function to find minimum value node in a given tree. TreeNode* findMin(TreeNode* node){ while(node && node->left != NULL) node = node->left; return node; } ``` #### 查询功能 除了上述增删改之外,另一个重要的方面就是如何高效地定位某个具体的键值位置或是判断两个指定节点之间的关系,比如求解它们之间最近共同祖先等问题[^2]。 ```cpp bool searchInBST(TreeNode* root,int target){ if(!root) return false; if(target<root->val) return searchInBST(root->left,target); else if(target>root->val) return searchInBST(root->right,target); else return true; } ``` 通过以上方法论可以较好地应对大部分基础性的二叉搜索树编程挑战。当然实际应用过程中还可能会遇到更多复杂的场景需求进一步优化算法效率或增强鲁棒性等方面的工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值