1099. Build A Binary Search Tree (30)

#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

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

int in[110], index, first = 1;
queue<int> q;

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

	tree[root].key = in[index++];

	if(r != -1)
	{
		inorder(r);
	}
}

void bfs()
{
	int qsize = q.size(), cur, l, r;
	while(qsize--)
	{
		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);
		}
	}

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

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

	int i;
	for(i = 0; i < n; i++)
	{
		scanf("%d%d", &tree[i].lchild, &tree[i].rchild);
	}

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

	sort(in, in + n);
	inorder(0);

	q.push(0);
	bfs();

	printf("\n");

	system("pause");
	return 0;
}

 

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

导航