C语言二叉排序数算法

#include<stdio.h>
#define ARRAYLEN 10
int source[]={12,56,78,92,71,35,82,49,37,10};//增加到二叉排序树中的数据
typedef struct bst//4~9定义二叉排序树
{
int data;
struct bst *left;
struct bst *right;
}BSTree;
void InsertBST(BSTree *t,int key)//在二叉排序树中插入查找关键字key
{
BSTree *p,*parent,*head;
if(!(p=(BSTree *)malloc(sizeof(BSTree *))))//申请内存空间
{
printf("申请内存出错\n");
exit(0);
}
p->data=key;//保存结点数据
p->left=p->right=NULL;//左右子树置空
head=t;
while(head)//查找需要添加的父结点
{
parent=head;
if(key<head->data)//若关键字小于结点的数据
head=head->left;//在左子树上查找
else//若关键字大于结点的数据
head=head->right;//在右子树上查找
}
//判断添加到左子树还是右子树
if(key<parent->data)//小于父节点
parent->left=p;//添加到左子树
else//大于父结点
parent->right=p;//添加到右子树
}
void CreateBST(BSTree *t,int data[],int n)//将数组中的数据插入二叉排序树
{
int i;
t->data=data[0];//为根结点赋值
t->left=t->right=NULL;
for(i=1;i<n;i++)//循环处理,将数组元素添加到排序树中
InsertBST(t,data[i]);//调用函数,将一个元素添加到排序树中
}
void BST_LDR(BSTree *t)//中序遍历
{
if(t)//树不为空,则执行以下操作
{
BST_LDR(t->left);//中序遍历左子树
printf("%d ",t->data);//输出结点数据
BST_LDR(t->right);//中序遍历右子树
}
return ;
}
int main()
{
int key,i,pos;
BSTree bst;//保存二叉排序树根节点
CreateBST(&bst,source,ARRAYLEN);//创建二叉排序树
printf("遍历二叉排序树结果:");
BST_LDR(&bst);//遍历二叉排序树
getch();
return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值