文章目录
Author: CHEN, Yue
Organization: 浙江大学
Time Limit: 400 ms
Memory Limit: 64 MB
Code Size Limit: 16 KB
A1119 Pre- and Post-order Traversals (30point(s))
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
Code
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
struct NODE{
int data;
struct NODE *lchild,*rchild;
};
vector<int>pre,post,in;
NODE *creat(int preL,int preR,int postL,int postR){
if(preL>preR) return NULL;
NODE *root=new NODE;
root->data=pre[preL];
int i;
for(i=preL+1;i<=preR;i++){
if(pre[i]==post[postR-1]) break;
}
int lcnt=i-preL-1;
root->lchild=creat(preL+1,i-1,postL,postL+lcnt-1);
root->rchild=creat(i,preR,postL+lcnt,postR-1);
return root;
}
void inorder(NODE *root){
if(root==NULL) return;
inorder(root->lchild);
in.push_back(root->data);
inorder(root->rchild);
}
bool dfs(NODE *root){
if(root==NULL) return true;
if(root->lchild==NULL && root->rchild!=NULL) return false;
if(root->rchild==NULL && root->lchild!=NULL) return false;
return dfs(root->lchild) && dfs(root->rchild);
}
int main(){
int n;
cin>>n;
pre.resize(n+1);
post.resize(n+1);
for(int i=1;i<=n;i++) cin>>pre[i];
for(int i=1;i<=n;i++) cin>>post[i];
NODE* root=creat(1,n,1,n);
if(dfs(root)==true) printf("Yes\n");
else printf("No\n");
inorder(root);
for(int i=0;i<in.size();i++){
if(i==0) printf("%d",in[i]);
else printf(" %d",in[i]);
}
printf("\n");
return 0;
}
Analysis
-前序后序建树,如果建成的树有某个结点只有一个孩子,则该树不唯一。
-输出得到的树的中序遍历。

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



