1110. Complete Binary Tree (25)

#include <iostream>
#include <queue>
#include <string.h>

using namespace std;

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

queue<int> q;
int res = 1, flag, lastnode, bfscount;

int getindex(char s[])
{
	if(s[0] == '-')
	{
		return -1;
	}

	int i, len = strlen(s), index = 0;
	for(i = 0; i < len; i++)
	{
		index = s[i] - '0' + index * 10;
	}

	return index;
}

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

		if(cur == -1)
		{
			if(flag == 0)
			{
				continue;
			}
			else
			{
				qsize = q.size();
				while(qsize--)
				{
					cur = q.front();
					q.pop();

					if(cur != -1)
					{
						res = 0;
						return;
					}
				}

				return;
			}
		}
		else if(flag == 0)
		{
			lastnode = cur;
		}

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

		q.push(l);
		q.push(r);
	}

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

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

	int i;
	char a[5], b[5];

	for(i = 0; i < n; i++)
	{
		getchar();
		scanf("%s%s", a, b);

		tree[i].lchild = getindex(a);
		tree[i].rchild = getindex(b);
	}

	int root;
	for(i = 0; i < n; i++)
	{
		q.push(i);
		bfscount = 0;

		bfs();
		if(bfscount == n)
		{
			root = i;
			break;
		}
	}

	flag = 1;
	q.push(root);

	bfs();
	if(res == 1)
	{
		printf("YES %d\n", lastnode);
	}
	else
	{
		printf("NO %d\n", root);
	}

	system("pause");
	return 0;
}

 

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

导航