1086. Tree Traversals Again (25)

#include <iostream>
#include <stack>

using namespace std;

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

int pre[40], in[40], r = 1, first = 1;

int buildtree(int a, int b, int c, int d)
{
	int root = r++;
	tree[root].key = pre[a];
	tree[root].lchild = tree[root].rchild = -1;

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

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

	return root;
}

void postorder(int root)
{
	int l = tree[root].lchild, r = tree[root].rchild;
	if(l != -1)
	{
		postorder(l);
	}
	if(r != -1)
	{
		postorder(r);
	}

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

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

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

	int i, num, j = 1, k = 1;
	stack<int> s;
	char ch[5];

	for(i = 1; i <= 2 * n; i++)
	{
		getchar();
		scanf("%s", ch);

		if(ch[1] == 'u')
		{
			scanf("%d", &num);

			pre[j++] = num;
			s.push(num);
		}
		else
		{
			in[k++] = s.top();
			s.pop();
		}
	}

	buildtree(1, n, 1, n);
	postorder(1);

	printf("\n");

	system("pause");
	return 0;
}

 

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

导航