Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.
Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, first printf in a line Yes
if the tree is unique, or No
if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input 1:
7
1 2 3 4 6 7 5
2 6 7 4 5 3 1
Sample Output 1:
Yes
2 1 6 4 7 3 5
Sample Input 2:
4
1 2 3 4
2 4 3 1
Sample Output 2:
No
2 1 3 4
题解:由先序和后序推出中序遍历,由于先序和后序是无法确定一棵树的,如果存在某个根只有左孩子或右孩子,那么就是不唯一的,由于题目只要求给出其中一种的中序遍历就算正确,因此遇到无法确定的左右孩子时,将它归为右孩子,并且将flag只为false。
先序遍历的第一个结点(根左右)和后序遍历的最后一个结点(左右根)一定是根节点,然后通过后序遍历的倒数第二个结点一定是右子树(在根有左右子树的情况下)的第一个结点,来查找该结点在先序遍历中的位置可以确认该树的左子树的总结点数量和右子树的总结点数量,与他们的起始结束位置(范围)传递给递归函数。
最后通过递归来得出in的最终序列。(整体思路参考的柳神的题解)
#include<bits/stdc++.h>
using namespace std;
vector<int> pre, in, post;
bool flag = true;
void getIn(int preLeft, int preRight, int postLeft, int postRight){
if(pre[preLeft] == pre[preRight]){
in.push_back(pre[preLeft]);
return ;
}
int i = preLeft + 1;
while(pre[i] != post[postRight - 1]) i++;
if(i - preLeft == 1)
flag = false;
else
getIn(preLeft + 1, i - 1, postLeft, postLeft + (i - 1 - preLeft) -1);
in.push_back(post[postRight]);
getIn(i, preRight, postLeft + (i - 1 - preLeft), postRight - 1);
}
int main(){
int n, x;
scanf("%d", &n);
pre.resize(n), post.resize(n);
for(int i = 0; i < n; i++)
scanf("%d", &pre[i]);
for(int i = 0; i < n; i++)
scanf("%d", &post[i]);
getIn(0, n - 1, 0, n - 1);
printf("%s\n%d", flag == true ? "Yes" : "No", in[0]);
for(int i = 1; i < n; i++)
printf(" %d", in[i]);
printf("\n");
return 0;
}