A1127 ZigZagging on a Tree (30 分)

#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 35;
vector<int> level[maxn];
int in[maxn], post[maxn];
struct node
{
	int data,level;
	node *lchild, *rchild;
};
node* create(int inleft, int inright, int postleft, int postright,int index)
{
	if (inleft > inright) return NULL;
	node* root = new node;
	root->data = post[postright];
	root->level = index;
	int k;
	for (k = inleft; k <= inright; k++)
	{
		if (in[k] == post[postright]) break;
	}
	root->lchild = create(inleft, k - 1, postleft, postleft + k - 1 - inleft,index+1);
	root->rchild = create(k + 1, inright, postright - 1 - (inright - k - 1), postright - 1,index+1);
	return root;
}
void zigdfs(node* root)
{
	queue<node*> q;
	q.push(root);
	while (!q.empty())
	{	
		node* now = q.front();
		q.pop();
		//printf("%d ", now->data);
		level[now->level].push_back(now->data);
		if (now->lchild != NULL) q.push(now->lchild);
		if (now->rchild != NULL) q.push(now->rchild);//这里是now啊,错写成root还发现不了。。
	}
}
int main()
{
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) scanf("%d", &in[i]);
	for (int i = 0; i < n; i++) scanf("%d", &post[i]);
	node* root = create(0, n - 1, 0, n - 1, 0);
	zigdfs(root);
	int total = 0;
	int p = 0;
	while (level[p].size() != 0)
	{
		if (p % 2 == 1)
		{
			for (int j = 0; j < level[p].size(); j++)
			{
				printf("%d", level[p][j]);
				total++;
				if (total != n) printf(" ");
			}
		}
		else
		{
			for (int j = level[p].size() - 1; j >= 0; j--)
			{
				printf("%d", level[p][j]);
				total++;
				if (total != n) printf(" ");
			}
		}
		p++;
	}
		printf("\n");
		return 0;
}

思路比较清晰,先建树然后遍历。由于z字形输出,设置一个vector来存放各个行的数字个数,分奇偶来判断输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值