PAT-A 1119 题解
题意分析
这道题要求我们通过后序遍历和先序遍历的顺序还原一颗二叉树,同时把它的中序遍历顺序打印出来。
当然还必须判断,这样的二叉树是否是唯一的。
算法分析
本题的核心就在于还原出这个二叉树。首先我们得明白,什么情况下,我们不能还原出一颗唯一的二叉树?
答案就是,如果在先序遍历的序列中发发现,根节点后面的左右儿子结点只有一个,这个时候我们并不知道它到底是左儿子还是右儿子,所以产生了歧义。为了消除这个歧义,我们就直接假设它是左儿子。消除歧义的同时,给这个二叉树打上标记。
AC代码
#include<unordered_map>
#include<iostream>
#include<math.h>
#include<string>
int cnt = 0;
using namespace std;
bool is_unique = true;
unordered_map<int, int> pre_map, post_map;
int n;
const int MAX_N = 32;
struct node
{
node* lc, * rc;
int val;
};
int pre[MAX_N], post[MAX_N];
/*
判断是否唯一的标准是,当一个结点的子节点只有一个的时候,
我们无法判断它到底是左儿子还是右儿子。
由于答案要求输出一种结果即可,所以我们就默认他为左儿子。
*/
node* create_tree(int preL, int preR, int postR) {//postR表示post的根节点下标
if (preL > preR || postR < 1) return NULL;
node* root = new node();
root->val = pre[preL];
if(preL == preR){
root->lc = root->rc = NULL;
return root;
}
if(pre[preL+1] == post[postR-1]){//产生了左右儿子相同的情况
root->lc = create_tree(preL+1,preR,postR-1);
root->rc = NULL;
return root;
}
//右儿子在pre数组中的位置
int pre_rc_pos = pre_map[post[postR - 1]];
//左儿子在post数组中的位置
int post_lc_pos = post_map[pre[preL + 1]];
//右子树的结点个数
root->lc = create_tree(preL + 1, pre_rc_pos - 1, post_lc_pos);
root->rc = create_tree(pre_rc_pos, preR, postR - 1);
return root;
}
node* build(int preL, int preR, int postL, int postR) {
if (preL > preR || postL > postR || preL == 0 || postL == 0) return NULL;
node* root = new node;
root->val = pre[preL];//或者取post[postR]
if (preL == preR) {
root->lc = root->rc = NULL;
return root;
}
//右儿子在pre数组中的位置
int pre_rc_pos = pre_map[post[postR - 1]];
//左儿子在post数组中的位置
int post_lc_pos = post_map[pre[preL + 1]];
if (post[postR - 1] == pre[preL + 1]) {//当产生了左右儿子相同的情况
is_unique = false;
root->lc = build(preL + 1, preR, postL, postR - 1);
root->rc = NULL;
return root;
}
root->lc = build(preL + 1, pre_rc_pos - 1, postL, post_lc_pos);
root->rc = build(pre_rc_pos, preR, post_lc_pos + 1, postR - 1);
return root;
}
void inOrder(node* root) {
if (root == NULL) return;
inOrder(root->lc);
cout << root->val; cnt++;
if (cnt != n) {
cout << " ";
}
else cout << endl;
inOrder(root->rc);
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> pre[i];
pre_map[pre[i]] = i;
}
for (int i = 1; i <= n; i++) {
cin >> post[i];
post_map[post[i]] = i;
}
node* root = build(1, n,1, n);
string msg = is_unique ? "Yes" : "No";
cout << msg << endl;
inOrder(root);
system("pause");
return 0;
}