1115. Counting Nodes in a BST (30)

#include <iostream>
#include <queue>

using namespace std;

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

int index = -1, n1, n2;
queue<int> q;

void init(int root, int key)
{
	tree[root].key = key;
	tree[root].lchild = tree[root].rchild = -1;
}

void buildbst(int root, int key)
{
	if(index == -1)
	{
		init(++index, key);
		return;
	}

	int l = tree[root].lchild, r = tree[root].rchild, rootkey = tree[root].key;
	if(rootkey >= key)
	{
		if(l == -1)
		{
			tree[root].lchild = ++index;
			init(index, key);
		}
		else
		{
			buildbst(l, key);
		}
	}
	else
	{
		if(r == -1)
		{
			tree[root].rchild = ++index;
			init(index, key);
		}
		else
		{
			buildbst(r, key);
		}
	}
}

void bfs()
{
	int qsize = q.size(), cur, l, r;
	n1 = qsize;

	while(qsize--)
	{
		cur = q.front();
		q.pop();

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

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

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

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

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

	q.push(0);
	bfs();

	printf("%d + %d = %d\n", n1, n2, n1 + n2);

	system("pause");
	return 0;
}

 

posted on 2025-11-25 09:07  王景迁  阅读(4)  评论(0)    收藏  举报

导航