• 欢迎访问废江网站,承蒙遇见 QQ群
  • 本站将致力于推送优质的java知识以及算法,开源代码!

03-树2 List Leaves

浙大mooc 站点默认 4年前 (2019-11-05) 1633次浏览 已收录 0个评论 扫描二维码

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 –
2 7
– –
– –
5 –
4 6
Sample Output:
4 1 5

题意:给定一棵树,输出它的叶子结点,是层序输出

思路:既然给出的数是一组组数据,那最好就是用顺序存储的第二种方式(二叉树顺序存储第二种方式),一开始我以为结构体只需要两个数据,即左右地址,但是当我们输出的时候是输出结点值,此时我们还是需要第三个数据来存储结点的值,结点的值是啥?就是第一行值就是1,题目是从第0行开始的。之后,直接遍历就行了。实现了遍历,比如输出叶子结点,或者输出结点个数,或者计算结点值在二叉树的层次等等都易如反掌,这一类我在二叉树有一个专题(由二叉树遍历衍生出来的各种函数算法)。


废江博客 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:03-树2 List Leaves
喜欢 (0)
[]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址