二叉排序树

来源:互联网 发布:网络大神的小说 编辑:程序博客网 时间:2024/06/05 22:48

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

1221 20

示例输出

21 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);elseInsert(T->r,x);}}void in(p T){if(T){in(T->l);if(!sb){printf("%d",T->d);++sb;}elseprintf(" %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;}
0 0