码迷,mamicode.com
首页 > 编程语言 > 详细

二叉排序树

时间:2014-11-13 18:58:02      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   os   sp   for   

Time Limit: 1000MS Memory limit: 65536K

题目描述

在树结构中,有一种特殊的二叉树叫做排序二叉树,直观的理解就是——(1).每个节点中包含有一个关键值 (2).任意一个节点的左子树(如果存在的话)的关键值小于该节点的关键值 (3).任意一个节点的右子树(如果存在的话)的关键值大于该节点的关键值。现给定一组数据,请你对这组数据按给定顺序建立一棵排序二叉树,并输出其中序遍历的结果。
 

输入

输入包含多组数据,每组数据格式如下。
第一行包含一个整数n,为关键值的个数,关键值用整数表示。(n<=1000)
第二行包含n个整数,保证每个整数在int范围之内。

输出

为给定的数据建立排序二叉树,并输出其中序遍历结果,每个输出占一行。
 

示例输入

1
2
2
1 20

示例输出

2
1 20
恩 。。建树方式很简单,一开始sb想多了
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cctype>
#include <vector>
#include <cstdio>
#include <cmath>
#include <deque>
#include <stack>
#include <map>
#include <set>
#define ll long long
#define maxn 1010
#define pp pair<int,int>
#define INF 0x3f3f3f3f
#define max(x,y) ( ((x) > (y)) ? (x) : (y) )
#define min(x,y) ( ((x) > (y)) ? (y) : (x) )
using namespace std;
typedef struct node
{
	int d;
	node *l,*r;
}*p;
int n,sb;
void Insert(p &T,int x)
{
	if(T==NULL)
	{
		T=new node;
		T->l=NULL;T->r=NULL;
		T->d=x;
	}
	else
	{
		if(x<T->d)
			Insert(T->l,x);
		else
			Insert(T->r,x);
	}
}
void in(p T)
{
	if(T)
	{
		in(T->l);
		if(!sb)
		{
			printf("%d",T->d);
			++sb;
		}
		else
			printf(" %d",T->d);
		in(T->r);
	}
}
int main()
{
	while(~scanf("%d",&n))
	{
		p root=NULL;int x;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&x);
			Insert(root,x);
		}
		sb=0;
		in(root);puts("");
	}
	return 0;
}

二叉排序树

标签:des   style   blog   io   color   ar   os   sp   for   

原文地址:http://blog.csdn.net/qq_16255321/article/details/41082913

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!