数据结构之排序二叉树递归建立,递归查找

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define ElemType int
#define maxsize 20
typedef struct BSTNode
{
    ElemType data;
    struct BSTNode* lchild;
    struct BSTNode* rchild;
}*BSTTree,BSTNode;
int jjj=0;
//----------------中序遍历二叉树---------------
void InOrderTraverse(BSTTree bt)
{
    if(bt!=NULL)
    {
        InOrderTraverse(bt->lchild);
        printf("%d ",bt->data);
        InOrderTraverse(bt->rchild);
    }
}
//--------------二叉排序树的插入(递归)------------------
BSTTree BSTInsert(BSTTree t,ElemType x)
{
    if(t==NULL)
    {
        BSTNode* p=(BSTNode*)malloc(sizeof(BSTNode));
        p->data=x;
        p->lchild=NULL;
        p->rchild=NULL;
        t=p;
        return t;
        //printf("%d ",t->data);
    }
    else if(x<t->data)
        t->lchild=BSTInsert(t->lchild,x);
    else if(x>t->data)
        t->rchild=BSTInsert(t->rchild,x);
   // return true;
}

//-----------------二叉排序树的建立-------------
BSTTree BSTCreat(BSTTree t,ElemType* arr,int len)
{
    int i=0;
    for(i=0;i<len;i++)
    {
        t=BSTInsert(t,*(arr+i));
    }
    return t;
}
//------------二叉排序树的递归查找-------------
BSTNode* BSTFind(BSTTree t,ElemType x)
{
    if(!t)
        return NULL;
    else if(x<t->data)
        return BSTFind(t->lchild,x);
    else if(x>t->data)
        return BSTFind(t->rchild,x);
    else
        return t;

}
int main()
{
    BSTTree t=NULL;
    BSTNode* p;
    ElemType arr[6]={6,4,10,5,9,11};
    t=BSTCreat(t,arr,6);
    printf("二叉树中序遍历\n");
    InOrderTraverse(t);
    p=BSTFind(t,5);
    printf("\n%d ",p->data);


}

这里写图片描述

【注意】注意递归函数返回值的问题

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值