1102. Invert a Binary Tree (25)

#include <iostream>
#include <queue>

using namespace std;

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

queue<int> q;
int flag, first = 1, bfscount;

int getindex(char ch)
{
	if(ch >= '0' && ch <= '9')
	{
		return ch - '0';
	}

	return -1;
}

void print(int root)
{
	if(first == 1)
	{
		first = 0;
	}
	else
	{
		printf(" ");
	}

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

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

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

		if(flag == 1)
		{
			print(cur);
		}

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

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

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

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

	print(root);

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

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

	int i, l, r;
	char a, b;

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

		l = getindex(a);
		r = getindex(b);

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

		tree[i].key = i;
	}

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

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

	flag = 1;
	q.push(root);

	bfs();
	printf("\n");

	first = 1;
	inorder(root);
	printf("\n");

	system("pause");
	return 0;
}

 

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

导航