PAT A1127

代码如下,错误原因未知

#include<iostream>
#include<vector>
using namespace std;

int n, in[32], post[32];
struct node{
	int data;
	node *left, *right;
};
vector<int> v1, v2, v;
node* create(int postL, int postR, int inL, int inR) {
	if(postL > postR) return NULL;
	node* root = new node;
	root -> data = post[postR];
	int k = inL;
	while(post[postR] != in[k]) k++;
	int numLeft = k - inL;
	root -> left = create(postL, postL + numLeft - 1, inL, k - 1);	
	root -> right = create(postL + numLeft, postR - 1, k + 1, inR);
	return root;
}
void toRight(node* root) {
	if(root == NULL) return ;
	v1.push_back(root -> data);
	if(root -> right) toRight(root -> right);
	else toRight(root -> left);
}
void toLeft(node* root) {
	if(root == NULL) return ;
	v2.push_back(root -> data);
	if(root -> left) toLeft(root->left);
	else toLeft(root -> right);
}
int main() {
	cin >> n;
	v.resize(n + 1);
	for(int i = 0; i < n; i++) cin >> in[i];
	for(int i = 0; i < n; i++) cin >> post[i];
	node* root = create(0, n - 1, 0, n - 1);
	toRight(root -> left);
	toLeft(root -> right); 
	int size1 = v1.size(), size2 = v2.size();
	int i = 0, j = 0, lst = 1, rst = 2;
	while(i < size1) {
		v[lst] = v1[i++];
		if(lst % 2 == 1) lst += 2; 
		lst ++;
	}
	while(j < size2) {
		v[rst] = v2[j++];
		if(rst % 2 == 1) rst += 2;
		rst ++;
	}
	cout << root -> data;
	for(int i = 1; i <= n; i++)
		if(v[i] >  0) cout << " " << v[i];
	return 0;
}

AC代码

#include<iostream>
#include<vector>
#include<queue>
using namespace std;

int n, root, in[35], post[35], tree[35][2];
struct node{
	int index, deepth;
};
vector<int> result[35];

void dfs(int &index,int postL, int postR, int inL, int inR) {
	if(inL > inR) return ;
	index = postR;
	int k = inL;
	while(post[postR] != in[k]) k++;
	dfs(tree[index][0], postL, postL + k - inL - 1, inL, k - 1);
	dfs(tree[index][1], postL + k - inL, postR - 1, k + 1, inR);
}
void bfs() {
	queue<node> q;
	q.push({root, 0});
	while(!q.empty()) {
		node top = q.front();
		q.pop();
		result[top.deepth].push_back(post[top.index]);
		if(tree[top.index][0]) q.push({tree[top.index][0], top.deepth + 1});
		if(tree[top.index][1]) q.push({tree[top.index][1], top.deepth + 1});
	}
}
int main() {
	cin >> n;
	for(int i = 1; i <= n; i++) cin >> in[i];
	for(int i = 1; i <= n; i++) cin >> post[i];
	dfs(root, 1, n, 1, n); 
	bfs();
	cout << result[0][0];
	for(int i = 1; i < 35; i++) {
		if(i % 2 == 1) {
			for(int j = 0; j < result[i].size(); j++)
				cout << " " << result[i][j];
		} else {
			for(int j = result[i].size() - 1; j >= 0; j--)
				cout << " " << result[i][j];
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值