题目描述
给定一棵二叉树的先序和中序遍历结果,求后序。
Input
输入包含多组数据. 第一行一个n表示二叉树内的节点数 (1<=n<=1000). 下面两行分别表示先序遍历和中序遍历的序列 。
Output
对于每组数据在一行内输出该二叉树后序遍历序列.
Sample Input
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
Sample Output
7 4 2 8 9 5 6 3 1
在中序里找前序第一个pre[0],找到的位置i即为根节点,那么中序里[0,i-1]即是左子树,[i+1,n-1]即为右子树(n为中序序列的长度,下标从0开始的),同时前序的第一个元素(即根节点)就没用了,因为根节点已经构造出来了,那么就从pre[1]开始把前序序列pre分成两部分,怎么分呢?就是前半部分的长度和[0,i-1]长度相等,后半部分和[i+1,l-1]长度相等,然后这就有了两对分半的前序序列和后序序列,然后用这两对分别左右递归构造左右子树。
注意:每次分的前序和中序序列都必须保证长度相等!
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
int f;
int pre[1005], mid[1005];
struct BiNode
{
int data;
BiNode *lchild, *rchild;
};
BiNode *NewNode(int x)
{
BiNode *t = new BiNode;
t->lchild = t->rchild = NULL;
t->data = x;
return t;
}
BiNode *CreateTree(int *pre, int l1, int *mid, int l2)
{
int i, j, k;
for (i = 0; i < l2; i++)
{
if (pre[0] == mid[i])break;
}
BiNode *t = NewNode(mid[i]);
if (i > 0)
{
t->lchild = CreateTree(pre + 1, i, mid, i);
}
if (i < l2 - 1)
{
t->rchild = CreateTree(pre + i + 1, l2 - i - 1, mid + i + 1, l2 - i - 1);
}
return t;
}
void Print(BiNode *T)
{
if (T == NULL)return;
Print(T->lchild);
Print(T->rchild);
if (f)
cout << " ";
f = 1;
cout << T->data;
}
int main()
{
int n;
while (cin>>n)
{
for (int i = 0; i < n; i++)
cin >> pre[i];
for (int i = 0; i < n; i++)
cin >> mid[i];
BiNode *root;
root = CreateTree(pre, n, mid, n);
f = 0;
Print(root);
cout << endl;
}
return 0;
}