输出二叉树的所有叶子(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

一定要注意输出的最后一个结果后面是没有空格的(5后面没有空格),不然程序也是无法通过的,所以注意这个细节的处理。

#include<iostream>
using namespace std;
//#define Null -1;
#define Null -1
//想法是这样的:采用层次遍历输出,判断父结点左右孩子是否为空,为空则为叶子结点
struct Node
{
    int left;
    int right;
};
int main()
{
    //建树
    Node arr[10];
    int N;
    int count=0;
    cin>>N;
    char a,b;
    //还必须获得头结点的地址
    int arr2[10]={0};
    for(int i=0;i<N;i++)
    {
        cin>>a>>b;
        if(a!='-')
        {
            arr[i].left=a-'0';
            arr2[arr[i].left]=1;
        }
        else
            arr[i].left=Null;
        if(b!='-')
        {
            arr[i].right=b-'0';
            arr2[arr[i].right]=1;
        }
        else
            arr[i].right=Null;
        if(a=='-'&&b=='-')
            count++;
    }
    //找头结点地址
    int i;
    for(i=0;i<N;i++)
    {
        if(arr2[i]==0)
            break;
    }
    //树建好后,开始层次遍历,队里面应该放的是数组的下标
    int que[10];
    int front=-1,rear=-1;
    //首结点先入队
    que[++rear]=i;
    while(front<rear)
    {
        //出队
        i=que[++front];
        if(arr[i].left!=Null)
            que[++rear]=arr[i].left;
        if(arr[i].right!=Null)
            que[++rear]=arr[i].right;
        if(arr[i].left==Null&&arr[i].right==Null)
        {
            cout<<i;
            count--;
		    if(count)printf(" ");//注意空格的处理
            
        }
            
    }
    return 0;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是浩浩子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值