1064. Complete Binary Search Tree (30)

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

using namespace std;

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

int num[1010], r = 1, first = 1;
queue<int> q;

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 getindex(int a, int b)
{
	int count = b - a + 1, res, f = 1, base = 1;
	while(base < count)
	{
		base += f * 2;
		f *= 2;
	}

	f /= 2;
	base -= f * 2;
	res = (base + 1) / 2;

	if(base + f > count)
	{
		res += count - base;
	}
	else
	{
		res += f;
	}

	return res + a - 1;
}

int buildcbt(int a, int b)
{
	int index = getindex(a, b);
	int root = r++;

	tree[root].key = num[index];
	tree[root].lchild = tree[root].rchild = -1;

	if(index > a)
	{
		tree[root].lchild = buildcbt(a, index - 1);
	}
	if(index < b)
	{
		tree[root].rchild = buildcbt(index + 1, b);
	}

	return root;
}

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

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

	sort(num + 1, num + n + 1);
	buildcbt(1, n);

	q.push(1);
	bfs();

	printf("\n");

	system("pause");
	return 0;
}

 

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

导航