PTA 列出叶结点

279 阅读1分钟

对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。

输入格式:

首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。

输出格式:

在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

输出样例:

4 1 5

代码:

# include <queue>
# include <iostream>
using namespace std;

struct TNode
{
	int Right;
	int Left;
};

int main()
{
	int arr[10] = { 0 }, n, i, root;
	struct TNode T[10];
	char Left, Right;
	cin >> n;
	for (i = 0; i < n; i++)
	{
		cin >> Left >> Right;
		if (Left == '-')
			T[i].Left = -1;
		else
		{
			T[i].Left = Left - '0';
			arr[T[i].Left] = 1;
		}
		if (Right == '-')
			T[i].Right = -1;
		else
		{
			T[i].Right = Right - '0';
			arr[T[i].Right] = 1;
		}
	}
	for (i = 0; i < n; i++)
	{
		if (!arr[i])
		{
			root = i;
			break;
		}
	}

	queue<int> q;
	q.push(root);
	int flag = 0;
	while (q.size() > 0)
	{
		root = q.front();
		q.pop();
		if (T[root].Left == -1 && T[root].Right == -1)
		{
			if (flag)
				cout << " ";
			cout << root;
			flag = 1;
		}
		else
		{
			if (T[root].Left != -1)
				q.push(T[root].Left);
			if (T[root].Right != -1)
				q.push(T[root].Right);
		}
	}
	return 0;
}

提交结果: