PAT 1119 Pre- and Post-order Traversals

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

题目大意:根据前序后序遍历找中序遍历
思路:其实和其他的求遍历序列的方法类似, 即找根节点, 找左子树, 右子树节点个数, 这里难在于左子树右子树节点个数的求解方法
   后序遍历的倒数第二个节点就是右子树的根节点, 在前序遍历中找到这个节点就能在前序遍历中区分出左子树右子树, 从而得出左子树和右子树节点个数
   那么为什么前序中序遍历不能得到唯一的中序遍历呢?
   因为前序遍历的顺序是NLR, 后序遍历的顺序是LRN 当根节点只有一个子节点的 时候就不能判断该子节点是左节点还是右节点,因为是普通的二叉树, 不是查找二叉树, 节点之间没有大小关系, 因而中序遍历是不唯一的, 即由二叉树的前序后序遍历不能建立一颗唯一的二叉树
   所以当右子树根节点和根节点相邻则表示根节点只有一个子节点
#include<iostream>
#include<vector>
using namespace std;
vector<int> pre, in, post;
bool unique=true;//标记中序遍历是否唯一
void inOrder(int prel, int prer, int postl, int postr){
  if(prel>prer) return;
  if(prel==prer){
    in.push_back(pre[prel]);
    return;
  }
  int i=prel;
  //找右子树根节点
  while(i<=prer && postr-1>=0 && i>=0 && pre[i]!=post[postr-1]) i++;
  //右子树的根节点和根节点相邻则表示根节点只有一个子节点
  if(i-prel<=1) unique=false;
  inOrder(prel+1, i-1, postl, postl+i-(prel+1)-1);
  in.push_back(pre[prel]);
  inOrder(i, prer, postl+i-(prel+1), postr-1);
}
int main(){
  int n, i;
  scanf("%d", &n);
  pre.resize(n); post.resize(n);
  for(i=0; i<n; i++) scanf("%d", &pre[i]);
  for(i=0; i<n; i++) scanf("%d", &post[i]);
  inOrder(0, n-1, 0, n-1);
  printf("%s
%d", unique ? "Yes" : "No", in[0]);
  for(i=1; i<n; i++) printf(" %d", in[i]);
  cout<<endl;
  return 0;
}
 
 
原文地址:https://www.cnblogs.com/mr-stn/p/9539419.html