浙大数据结构习题 03-树2 List Leaves

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a “-” will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in one line all the leaves’ indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line

Sample Input:

8
1 - // 结点0
- - // 结点1,以此类推
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

4 1 5

个人理解

首先是构建二叉树,我们只需输入每个结点的左儿子和右儿子的编号即可,输入的当前这个结点编号是默认按照0~N-1的顺序给定的。这里题意没有讲清楚,一开始我有点搞不清。

之后题目要求要按照从上到下,从左到右的顺序输出叶结点的编号,其实就是层序遍历。

完整代码如下:

#include<iostream>
#include<queue>
#define null -1 //这里注意不要加分号,这样null就变成了-1;,而不是-1

using namespace std;

struct TreeNode
{
	int data;
	int left;
	int right;
}T[10];

int BuildTree(struct TreeNode T[])
{
	int n;
	char left;
	char right;
	int check[10];
	int root;

	cout << "请输入结点个数:" << endl;
	cin >> n;
	if (!n)
	{
		return null;// 若结点个数为零,返回null(-1)
	}
	else
	{
		cout << "请依次输入结点的左结点和右结点" << endl;
		for (int i = 0; i < n; i++)
		{
			T[i].data = i;
			cin >> left >> right;
			
			if (left != '-')
			{
				T[i].left = left - '0';
				check[T[i].left] = 1;
			}
			else
			{
				T[i].left = null;
			}
			
			if (right != '-')
			{
				T[i].right = right - '0';
				check[T[i].right] = 1;
			}
			else
			{
				T[i].right = null;
			}
		}

		for (int i = 0; i < 10; i++)
		{
			if (check[i] != 1)
			{
				root = i;
				break;
			}
		}
		
		return root;
		
	}
	

}

void PrintLeaves( int root) // 采用层序遍历,将根结点传入参数 
{
	queue<struct TreeNode> q;// 使用int型队列来存贮每个结点的下标
	struct TreeNode temp;

	if (root == null)
	{
		cout << "二叉树为空" << endl;
		return;
	}
	else	
	{
		q.push(T[root]);
		while (!q.empty())
		{
			temp = q.front();// 将队列首元素赋给临时变量temp
			q.pop();// 弹出
			if (temp.left==null && temp.right==null)// 左,右子树皆不存在,则为叶结点,输出叶结点
			{
				cout << temp.data << " ";
			}
			if (temp.left != null) //不是叶结点就将左右儿子入队
			{
				q.push(T[temp.left]);
			}
			if (temp.right != null)
			{
				q.push(T[temp.right]);
			}
			 
			
		}
	}
}

void PrintNode(int root)//按照结点的编号顺序输出一遍,我用来检查BuildTree函数是否有误的
{
	for (int i = 0; i < 6; i++)
	{
		cout << T[i].data << " " << T[i].left << " " << T[i].right << endl;
	}
}



int main()
{
	int r = BuildTree(T);
	cout << "根结点为结点" << r << endl;
	cout << "叶结点为:";
	PrintLeaves(r);
	

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值