PTA7-4 列出叶结点

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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

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

typedef struct TreeNode {
    struct TreeNode* left;
    struct TreeNode* right;
    struct TreeNode* parent;
    int var;
}TreeNode;

string str;//存放叶子节点下标

//层序遍历寻找叶子结点
void LevelOrder(TreeNode* root) {
    int num = 0;//空格判定
    int size = str.size();
    queue<TreeNode*> q;
    if (root) q.push(root);
    while (!q.empty()) {
        TreeNode* front = q.front();
        q.pop();
        //如果为叶子节点 则输出
        if (str.find(front->var+'0') != -1) {
            if (++num != size) {
                printf("%d ", front->var);
            }
            else
                printf("%d", front->var);
        }
        if (front->left) {
            q.push(front->left);
        }
        if (front->right) {
            q.push(front->right);
        }
    }
}

int main()
{
    int N;
    cin >> N;
    getchar();
    //构建二叉树
    TreeNode* root[N];//N个节点
    for (int i = 0; i < N; i++){
        root[i] = (TreeNode*)malloc(sizeof(TreeNode));
        root[i]->parent = NULL;
    }
    char ch1, ch2;
    for (int i = 0; i < N; i++) {
        cin >> ch1 >> ch2;
        root[i]->var = i;
        if (ch1 == ch2) {
            root[i]->left = NULL;
            root[i]->right = NULL;
            str.push_back(i + '0');
        }
        else if (ch1 == '-') {
            root[i]->left = NULL;
            root[i]->right = root[ch2 - '0'];
            root[ch2 - '0']->parent = root[i];
        }
        else if(ch2 == '-'){
            root[i]->right = NULL;
            root[i]->left = root[ch1 - '0'];
            root[ch1 - '0']->parent = root[i];
        }
        else{
            root[i]->left = root[ch1-'0'];
            root[i]->right = root[ch2 - '0'];
            root[ch1 - '0']->parent = root[i];
            root[ch2 - '0']->parent = root[i];
        }
    }

    //找主根
    for (int i = 0; i < N; i++)
    {
        if (root[i]->parent == NULL) {
            LevelOrder(root[i]);
            break;
        }
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值