列出叶结点 (25分)

对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。

输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 “-”。编号间以 1 个空格分隔。

输出格式:
在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

输出样例:

4 1 5

直接代码:

#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
struct node
{
    int left,right;
};
node T1[10];
int creat(node *t)
{
    int n;
    cin>>n;
    int check[n];
    for(int i(0);i<n;i++)
    {
        check[i]=0;
    }
    for(int i(0);i<n;i++)
    {
        char l,r;
        cin>>l>>r;
        if(l=='-')
        {
            t[i].left=-1;
        }
        else
        {
            t[i].left=l-'0';
            check[t[i].left]=1;
        }
        if(r=='-')
        {
            t[i].right=-1;
        }
        else
        {
            t[i].right=r-'0';
            check[t[i].right]=1;
        }
    }
    for(int i(0);i<n;i++)
    {
        if(check[i]==0)
        {
            return i;
        }
    }
    return -1;
}
int flag=0;
void cengxubianli(int r,node *t)
{
    int in=0;
    int out=0;
    int a[100];
    a[in++]=r;
    while (in>out)
    {
        if(a[out]!=-1)
        {
            
            if(t[a[out]].left==-1&&t[a[out]].right==-1)
            {
                if(flag==0)
                {
                    cout<<a[out];
                    flag=1;
                }
                else if(flag==1)
                {
                    cout<<" "<<a[out];
                }
            }
            a[in++]=t[a[out]].left;
            a[in++]=t[a[out]].right;
             
    }
        out++;
    }
}

int main()
{
    int root;
    root=creat(T1);
    cout<<root<<endl;
    cengxubianli(root, T1);
}

Work Hard, Stay Humble!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值