PTA List Leaves (25分)

给定一棵树的节点数,按照从上到下、从左到右的顺序列出所有叶子节点的编号。输入包含每个节点的左右子节点信息,输出叶子节点的编号。思路是通过层次遍历,从根节点开始,只打印没有子节点的节点。代码实现未包含注释。
摘要由CSDN通过智能技术生成

7-2 List Leaves (25分)

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.

草率了这张截图

思路
题目的大意是按顺序给出每个节点的左右子树的序号,序号从0开始,空子树对应符号‘ - ’,我们要按层次遍历打印出叶子节点的序号;
我们可以改动一下层次遍历代码的小部分,即只打印左右子树都为空的节点的序号就能完成题目,但是层次遍历怎么开始呢?
题目给了左右子树,所以我们只需要找到树头节点序号,从头节点开始,层次遍历节点即可啦,了解题意了就看代码把,代码才是精髓,啊我半夜1点在这里打博客,不太自律啊,代码注释没写,有问题->评论或私信
代码

#include <iostream>
using namespace std;
struct Node{
   
    int index;
    char left;
    char right;
    int leftIndex;
    int rightIndex;
}Tree[10];
int main(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值