PTA_07_03_树2_list leaves(详细讲解)

这篇博客介绍了如何使用C++实现层序遍历算法来查找并按特定顺序输出二叉树的所有叶节点。通过创建队列、处理输入数据构建树结构,并设计层序遍历函数,实现了从上到下、从左到右的叶节点输出。程序首先读取节点信息,然后使用队列进行层序遍历,当遇到叶节点时将其输出。这个过程对于理解和实现树的遍历算法具有指导意义。
摘要由CSDN通过智能技术生成

PTA_07_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.

给定一棵树,你应该按照从上到下,从左到右的顺序列出所有的叶子。

输入规格

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.

每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数N(≤10),这是树中的节点总数——因此节点编号从0到N−1。接下来是N行,每一行对应一个节点,并给出该节点的左右子节点的索引。如果孩子不存在,一个“-”将放在位置。任何一对孩子都被一个空间隔开。

输入样式

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

输出规格

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.

对于每个测试用例,按从上到下、从左到右的顺序在一行中打印所有叶子的索引。任何相邻的数字之间必须正好有一个空格,并且在行尾没有额外的空格。

输出样式
4 1 5
算法分析

叶节点的定义:树中没有子结点(度为0)的结点称为是叶节点,叶节点又被称为终端结点

由输入进行分析:

index 0 1 2 3 4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值