1020. Tree Traversals (25)

#include <iostream>
#include <queue>

using namespace std;

struct node
{
	int lchild, rchild, key;
}tree[40];

int post[40], in[40], r, first = 1;
queue<int> q;

int buildtree(int a, int b, int c, int d)
{
	int root = r++;

	tree[root].key = post[b];
	tree[root].lchild = tree[root].rchild = -1;

	int i;
	for(i = c; i <= d; i++)
	{
		if(post[b] == in[i])
		{
			break;
		}
	}

	if(i > c)
	{
		tree[root].lchild = buildtree(a, a + i - c - 1, c, i - 1);
	}
	if(i < d)
	{
		tree[root].rchild = buildtree(a + i - c, b - 1, i + 1, d);
	}

	return root;
}

void bfs()
{
	int size = q.size(), cur, l, r;
	while(size--)
	{
		cur = q.front();
		q.pop();

		if(first == 1)
		{
			first = 0;
		}
		else
		{
			printf(" ");
		}

		printf("%d", tree[cur].key);

		l = tree[cur].lchild;
		r = tree[cur].rchild;

		if(l != -1)
		{
			q.push(l);
		}
		if(r != -1)
		{
			q.push(r);
		}
	}

	size = q.size();
	if(size > 0)
	{
		bfs();
	}
}

int main()
{
	int n;
	scanf("%d", &n);

	int i;
	for(i = 0; i <= n - 1; i++)
	{
		scanf("%d", &post[i]);
	}
	for(i = 0; i <= n - 1; i++)
	{
		scanf("%d", &in[i]);
	}

	buildtree(0, n - 1, 0, n - 1);

	q.push(0);
	bfs();

	printf("\n");

	system("pause");
	return 0;
}

 

posted on 2025-11-23 16:57  王景迁  阅读(0)  评论(0)    收藏  举报

导航