数据结构上机实验-二叉排序树的创建



二叉排序树

       二叉排序树(Binary Sort Tree)又称二叉查找树(Binary Search Tree),亦称二叉搜索树

二叉排序树或者是一棵空树,或者是具有下列性质的 二叉树
(1)若左子树不空,则左子树上所有结点的值均小于它的 根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。


           二叉排序树经过中序遍历之后可得到递增序列。

本代码参考2005年华中科技大学计算机保研机试真题

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct node
{
	int key;
	struct node *l,*r;
}bstnode;
int bstinsert(bstnode *&p,int k)
{
	if(p==NULL)
	{
		p=new bstnode();
		p->key=k;
		p->l=p->r=NULL;
		return 1;
	}
	else if(k==p->key)//去重 
	return 0;
	else if(k<p->key)
	return bstinsert(p->l,k);
	else 
	return bstinsert(p->r,k);
}
void build(bstnode *&bt,int *str,int n)
{
	bt=NULL;
	for(int i=0;i<=n-1;i++)
	{
		bstinsert(bt,str[i]);//每次插入都从树头开始
	}
}
void preorder(bstnode *bt)
{
	if(bt!=NULL)
	{
		printf("%d ",bt->key);
		preorder(bt->l);
		preorder(bt->r);
	}
}
void inorder(bstnode *bt)
{
	if(bt!=NULL)
	{
		inorder(bt->l);
		printf("%d ",bt->key);
		inorder(bt->r);
	}
}
void posorder(bstnode *bt)
{
	if(bt!=NULL)
	{
		posorder(bt->l);
		posorder(bt->r);
		printf("%d ",bt->key);
	}
}
int main()
{
	int n;
	int num[10120];
	while(~scanf("%d",&n))
	{
		for(int i=0;i<n;i++)
		{
			scanf("%d",&num[i]);
		}
		bstnode *nd=new bstnode();
		build(nd,num,n);
		preorder(nd);
		printf("\n");
		inorder(nd);
		printf("\n");
		posorder(nd);
		printf("\n");
	}
	return 0;
} 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值