迷失の搜索树
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
小璐在机缘巧合之下获得了一个二叉搜索树,这个二叉搜索树恰好有n个节点,每个节点有一个权值,每个节点的权值都在[1,n]这个区间内,并且两两不相同,真是优美的性质啊
但是命运的不公又让她失去了这个二叉搜索树
幸运的是,她还记得自己丢失的二叉搜索树的前序遍历序列。
在丢了二叉搜索树之后,小璐无比想念她的这个树的后序遍历
那么问题来了,聪明的你在知道这个二叉搜索树的前序遍历的序列的情况下,能帮她找到这个二叉搜索树的后序遍历嘛?
Input
多组输入,以文件结尾
每组数据第一行为一个整数n,代表这个二叉搜索树的节点个数(1<=n<=100)
接下来一行n个整数,代表这个二叉搜索树的前序遍历序列
Output
输出n个整数
表示这个二叉树的后序遍历序列
Example Input
5 4 2 1 3 5
Example Output
1 3 2 5 4
Hint
二叉查找树是一棵空树,或者是具有下列性质的二叉树:
若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值
若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值
它的左、右子树也分别为二叉排序树
Author
2016暑假集训结训赛 by QAQ
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{int data;struct note *l,*r;
};
int k;
int a[110],b[110];
struct node *creat(int n,int *a,int *b)
{struct node *root;int i;if(n == 0)return NULL;root = (struct node *)malloc(sizeof(struct node));root->data = a[0];for(i = 0;i <n;i++){if(b[i] == a[0])break;}root->l = creat(i,a+1,b);root->r = creat(n-i-1,a+i+1,b+i+1);return root;
}
void hou(struct node *root)
{if(root!=NULL){hou(root->l);hou(root->r);a[k++] = root->data;}
}
int main()
{int n,i,j,t;while(scanf("%d",&n) != EOF){for(i = 0;i <n;i++){scanf("%d",&a[i]);b[i] = a[i];}for(i = 0;i <n-1;i++) // 排序为中序遍历{for(j = 0;j < n-i-1;j++){if(b[j] > b[j+1]){t = b[j];b[j] = b[j+1];b[j+1] = t;}}}struct node *root;root = creat(n,a,b);k = 0;hou(root);for(i = 0;i <n;i++){if(i < n-1)printf("%d ",a[i]);elseprintf("%d\n",a[i]);}}return 0;
}