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(