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
二叉查找树是一棵空树,或者是具有下列性质的二叉树:
若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值
若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值
它的左、右子树也分别为二叉排序树
code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int a[1100], t;
struct node
{
int data;
struct node *lchild, *rchild;
};
void InOrder(struct node *root)
{
if(root)
{
InOrder(root->lchild);
InOrder(root->rchild);
a[t++] = root->data;
}
}
struct node *recreat(int x, struct node *root)
{
if(root == NULL)
{
root = (struct node*)malloc(sizeof(struct node));
root->data = x;
root->lchild = root->rchild = NULL;
return root;
}
else
{
if(x>root->data)
{
root->rchild = recreat(x, root->rchild);
}
else if(x<root->data)
{
root->lchild = recreat(x, root->lchild);
}
}
return root;
}
int main()
{
int n;
while(~scanf("%d", &n))
{
struct node *root;
int i;
t = 0;
root = NULL;
for(i = 0;i<n;i++)
{
int x;
scanf("%d", &x);
root = recreat(x, root);
}
InOrder(root);
for(i = 0;i<n;i++)
{
if(i==n-1) printf("%d\n", a[i]);
else printf("%d ", a[i]);
}
}
}
本文介绍了一种根据二叉搜索树的前序遍历序列重构树并输出后序遍历的方法。通过递归创建二叉树节点并进行中序遍历来实现。适用于计算机科学中的数据结构与算法学习。
1710

被折叠的 条评论
为什么被折叠?



