pta 7-6 列出叶结点

#include<bits/stdc++.h>
using namespace std;

typedef struct TNode *Tree;
struct TNode
{
    int data;
    struct TNode *Left;
    struct TNode *Right;
};
int flag[10]; //寻找根结点
struct Node
{
    int left, right;
}num[10];

Tree Build(int node)
{
    Tree t = (Tree) malloc(sizeof(struct TNode));
    t->data = node;
    t->Left = t->Right = NULL;
    if(num[node].left != 100) t->Left = Build(num[node].left);
    if(num[node].right != 100) t->Right = Build(num[node].right);
    return t;
}

void Print(Tree T)
{
    if(T == NULL) return;
    Tree queue[10];
    int left=0, right=0;
    queue[right++] = T;

    int cnt = 0; //计数,空格输出控制
    while (left < right)
    {
        Tree t = queue[left++];
        if(t->Left==NULL && t->Right==NULL) {
            if(cnt == 0) printf("%d", t->data);
            else printf(" %d", t->data);
            cnt++;
        }
        if (t->Left) queue[right++] = t->Left;
        if (t->Right) queue[right++] = t->Right;
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    getchar();
    for(int i=0; i<n; i++)
    {
        char x, y;
        scanf("%c %c",&x, &y);
        getchar();
        if(x == '-') num[i].left = 100;
        else
        {
            num[i].left = x - '0';
            flag[x - '0'] = 1;
        }

        if(y == '-') num[i].right = 100;
        else
        {
            num[i].right = y - '0';
            flag[y - '0'] = 1;
        }
    }
    int node;
    for(int i=0; i<n; i++)
    {
        if(flag[i] == 0) node = i;
    }

    Tree t = Build(node);
    Print(t);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值