1119 Pre- and Post-order Traversals

知识点:二叉树

属于是PAT上面不错的题,考察对二叉树遍历的理解,这道题只要想清楚什么情况出现了二叉树就不唯一了就可以做出来了。

然后就是PAT的坑,格式错误,最后要输出换行,因为知道PAT要求严格,所以最后一行最后一个数据后面什么都不敢输出的,然后因为没有输出换行错了。

#include <bits/stdc++.h>

using namespace std;

struct node {
	int val;
	int lchild, rchild;
} tree[35];

int tot, pre[35], post[35], cnt;
bool flag = true;

int create(int prel, int prer, int postl, int postr) {
	if (prel > prer) return -1;
	int root = ++tot;
	tree[root].val = pre[prel];
	int k = postl - 1;
	for (int i = postl; i <= postr - 1; i++) {
		if (pre[prel + 1] == post[i]) { k = i; break; }
	}
	if (k == postr - 1 && postr != postl) flag = false;
	int numleft = k - postl + 1;
	tree[root].lchild = create(prel + 1, prel + numleft, postl, postl + numleft - 1);
	tree[root].rchild = create(prel + numleft + 1, prer, postl + numleft, postr - 1);
	return root;
}

void inorder(int root) {
	if (root == -1) return;
	inorder(tree[root].lchild);
	if (cnt++) cout << " ";
	cout << tree[root].val;
	inorder(tree[root].rchild);
}

int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) cin >> pre[i];
	for (int i = 0; i < n; i++) cin >> post[i];
	int root = create(0, n - 1, 0, n - 1);
	cout << (flag ? "Yes" : "No") << endl;
	inorder(root);
	cout << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值