PAT 甲级 1119 Pre- and Post-order Traversals (30 分)

Note

  • 根据前序+后序确定这棵二叉树,只有一个孩子的的情况被视作不唯一(孩子可左可右)。
  • 建树 – bfs确定unique – 中序遍历输出结果
  • 最后需要多输出一个换行符
  • 前两次备考都直接跳过这道题,这次居然一下AC了,巨开心!

Code

#include<bits/stdc++.h>
using namespace std;

bool flag = true;  // unique
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值