您的位置:首页 > 其它

hdu3999 the order of a tree - BST二叉搜索树的前序遍历

2012-07-27 21:25 465 查看
hdu3999 the order of a tree

二叉搜索树(BST)

跟字典树相比,BST占用的资源少很多

所以要不要释放资源都无所谓?

还是养成一个好习惯吧,,

#include<iostream>
using namespace std;

struct BST
{
	int num;
	BST *lson,*rson;
	BST()
	{
		num=-1;
		lson=rson=0;
	}
} ;

BST *insert(BST *p,int x)
{
	if(!p)
	{
		p=new BST;
		p->num=x;
		return p;
	}
	
	if(x<p->num)
		p->lson=insert(p->lson,x);
	if(x>p->num)
		p->rson=insert(p->rson,x);
	
	return p;
}

void pre_traversal(BST *p,bool blank)
{
	if(p)
		if(blank==0)
			printf("%d",p->num);
		else
			printf(" %d",p->num);
	
	if(p->lson) pre_traversal(p->lson,1);
	if(p->rson) pre_traversal(p->rson,1);
}

void Free(BST *p)
{
	if(p->lson) Free(p->lson);
	if(p->rson) Free(p->rson);
	if(p) delete p;
}

int main()
{
	int n,x,i;      //n个数
	while(scanf("%d",&n)!=EOF)
	{
		BST *p=0;
		for(i=1;i<=n;i++)
		{
			scanf("%d",&x);
			p=insert(p,x);
		}
		pre_traversal(p,0);
		printf("\n");
		Free(p);                    //可能因为这题数据较弱,Free的效果不明显,, 
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: