算法:数据结构二叉排序树的建立和查找

文章介绍了如何在C语言中使用递归实现二叉搜索树(BST)的数据结构,包括BST的插入、查找功能以及中序遍历方法,展示了如何创建一个BST并进行操作。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
typedef int KeyType;
typedef struct BSTNode{
    KeyType key;
    struct BSTNode *lchild,*rchild;
}BSTNode,*BiTree;
//递归
int BST_Insert(BiTree &T,KeyType k)
{
    if(NULL==T)
    {
        //为新结点申请空间,第一个作为树根,后面递归再进入的不是树根,是为叶子结点
        T= (BiTree)calloc(1,sizeof(BSTNode) );
        T->key=k;
        return 1;
    } else if(k==T->key)
        return 0;//发现相同元素,不插入,考研不考
    else if(k<T->key)
        return BST_Insert(T->lchild,k);
    else
        return BST_Insert(T->rchild,k);
}
void  Creat_BST(BiTree &T,KeyType *str,int n)
{
    T=NULL;//T是树根
    int i=0;
    while (i<n)
    {
        BST_Insert(T,str[i]);//把某一个结点放入二叉树
        i++;
    }
}
void InOrder(BiTree T)
{
    if(T!=NULL)
    {
        InOrder(T->lchild);
        printf("%3d",T->key);
        InOrder(T->rchild);
    }
}
BSTNode *BST_Search(BiTree T,KeyType key,BiTree &p)
{
    p=NULL;
    while (T!=NULL&&key!=T->key)
    {
        p=T;
        if (key<T->key)
            T=T->lchild;
        else
            T=T->rchild;
    }
    return T;
}
int main() {
    BiTree T=NULL;//树根
    BiTree parent;//存储父亲结点的地址值
    BiTree search;
    KeyType str[7]={54,20,66,40,28,79,58};
    Creat_BST(T,str,7);
    InOrder(T);
    printf("\n");
    search= BST_Search(T,41,parent);
    if(search)
    {
        printf("find key %d\n",search->key);
    } else
    {
        printf("not found\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序garbage

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值