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

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

 

 

#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];
	printf("输入节点数n:\n");
	while(~scanf("%d",&n))
	{
		printf("输入n个节点值:\n");
		for(int i=0;i<n;i++)
		{
			scanf("%d",&num[i]);
		}
		bstnode *nd=new bstnode();
		build(nd,num,n);
		printf("先序遍历结果:\n");
		preorder(nd);
		printf("\n");
		printf("中序遍历结果:\n");
		inorder(nd);
		printf("\n");
		printf("后序遍历结果:\n");
		posorder(nd);
		printf("\n");
	}
	return 0;
}