Note
- 根据前序+后序确定这棵二叉树,只有一个孩子的的情况被视作不唯一(孩子可左可右)。
- 建树 – bfs确定unique – 中序遍历输出结果
- 最后需要多输出一个换行符
- 前两次备考都直接跳过这道题,这次居然一下AC了,巨开心!
Code
#include<bits/stdc++.h>
using namespace std;
bool flag = true;
vector<int> pre, post, in;
struct node{
int val;
node *left, *right;
};
node* new_node(int n) {
node* newnode = new node;
newnode->val = n;
newnode->left = newnode->right = NULL;
return newnode;
}
void create(node* &root, int prl, int prr, int pol, int por) {
if(prl > prr || pol > por) return ;
int i = pol, pre_prl = pre[prl];
if(root == NULL) {
root = new_node(pre_prl);
}
while(i <= por && post[i] != pre[prl]) i++;
if(i == por) {
if(root->val == pre_prl) {
create(root, prl + 1, prr, pol, por - 1);
}
else {
root->right = new_node(pre_prl);
create(root->right, prl + 1, prr, pol, por - 1);
}
}
else {
if(i == pol) {
root->left = new_node(pre_prl);
create(root->right, prl + 1, prr, pol + 1, por);
}
else {
create(root->left, prl, prl + i - pol, pol, i);
create(root->right, prl + i - pol + 1, prr, i + 1, por);
}
}
}
void inorder(node *root) {
if(root == NULL) return ;
inorder(root->left);
in.push_back(root->val);
inorder(root->right);
return ;
}
void bfs(node *root) {
queue<node*> q;
q.push(root);
while(!q.empty()) {
node* t = q.front();
q.pop();
if(t->left != NULL) q.push(t->left);
if(t->right != NULL) q.push(t->right);
if((t->left != NULL && t->right == NULL) ||
(t->left == NULL && t->right != NULL)) {
flag = false;
return ;
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data.txt", "r", stdin);
#endif
int n;
cin >> n;
pre.resize(n);
post.resize(n);
for(int i = 0; i < n; ++i) cin >> pre[i];
for(int i = 0; i < n; ++i) cin >> post[i];
node *root = NULL;
create(root, 0, n - 1, 0, n - 1);
inorder(root);
bfs(root);
if(flag) printf("Yes\n");
else printf("No\n");
for(int i = 0; i < n; ++i) {
if(i != 0) printf(" ");
printf("%d", in[i]);
}
printf("\n");
return 0;
}
|