数据结构MOOC 03-树2 List Leaves

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 -
2 7
- -
- -
5 -
4 6

Sample Output:

4 1 5

Solution:

题目要求通过输入节点数以及每个节点的左儿子和右儿子,从上到下打印出叶节点。解题的关键是通过层序遍历找到叶子结点去输出。

根据题意搭建程序框架:

int main() {
   
	输入建立二叉树
	寻找叶子结点并输出
}

程序的框架较为简单,只需要两个函数就可以完成题目要求,接下来分析两个函数的实现方法。

① 输入建立二叉树函数

根据题目的输入要求,我们可以使用静态链表即结构体数组的方式来存储二叉树。

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

输入的第几行就是代表该节点的值为几。例如样例输入中第0行的1 -代表值为0的节点左孩子的值为1,即指向第1行,右孩子为空(-1),建树应该是这样:img

二叉树根结点的位置不一定位于输入的第一行,因此在建二叉树的过程中,找出所建二叉树的根结点很关键。我们在建树的过程中寻找根结点的位置就可以通过遍历结构体数组中左右子树指向的下标,缺少的那个下标即是根结点所在下标。遍历的方法可以是创建一个 check[] 数组,初始化所有位置数值都为 0,然后在所有输入的左右子树的下标对应的 check[] 数值记为 1,最后遍历 check[] 数组找到数值为 0 的下标即是根结点所在位置。

// 读取数据建二叉树的函数,返回根结点的下标
int buildTree(Tree t[])
{
   
    int root = -1;    // s根结点位置下标
    cin >> N;
    char l, r;
    int check[10] = {
   0};
    for(int i=0; i<N; i++)
    {
   
        t[i].data = i;
        cin >> l >> r;
        if (l != '-')
        {
   
            t[i].left = l - '0';    // 将字符转化为整型
            check[t[i].left] = 1;
        }
        else
            t[i].left = -1;
        if (r 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值