博客
关于我
【树的应用】——列出叶结点 (25分)(附测试点)
阅读量:99 次
发布时间:2019-02-26

本文共 1902 字,大约阅读时间需要 6 分钟。

为了解决这个问题,我们需要构建一个二叉树,并按从上到下、从左到右的顺序输出所有叶节点的编号。叶节点是指没有左孩子和右孩子的节点。

方法思路

  • 读取输入:首先读取输入数据,确定树的节点总数和每个节点的左、右孩子。
  • 构建树结构:使用数组来表示每个节点的左、右孩子和节点值。
  • 确定根节点:根节点是没有作为任何其他节点左或右孩子出现的节点。
  • 层次遍历:使用队列来进行层次遍历,检查每个节点是否为叶节点,并收集这些叶节点。
  • 输出结果:将收集到的叶节点编号按顺序输出。
  • 解决代码

    #include 
    #include
    #include
    using namespace std;struct Node { int data; int left; int right;};int main() { int n; cin >> n; Node nodes[n]; for (int i = 0; i < n; ++i) { char a, b; cin >> a >> b; nodes[i].left = (a != '-') ? (a - '0') : -1; nodes[i].right = (b != '-') ? (b - '0') : -1; nodes[i].data = i; } bool used[n] = {false}; for (int i = 0; i < n; ++i) { int left = nodes[i].left; int right = nodes[i].right; if (left != -1 && left < n) { used[left] = true; } if (right != -1 && right < n) { used[right] = true; } } int root = -1; for (int i = 0; i < n; ++i) { if (!used[i]) { root = i; break; } } queue
    q; vector
    result; q.push(root); while (!q.empty()) { int current = q.front(); q.pop(); if (nodes[current].left == -1 && nodes[current].right == -1) { result.push_back(current); } if (nodes[current].left != -1) { q.push(nodes[current].left); } if (nodes[current].right != -1) { q.push(nodes[current].right); } } if (!result.empty()) { cout << result[0]; for (int i = 1; i < result.size(); ++i) { cout << " " << result[i]; } } return 0;}

    代码解释

  • 读取输入:读取节点总数n,然后读取每个节点的左、右孩子信息,构建树结构。
  • 确定根节点:使用一个布尔数组标记每个节点是否被作为子节点使用,根节点是未被标记的节点。
  • 层次遍历:使用队列进行层次遍历,检查每个节点是否为叶节点,并将叶节点编号收集起来。
  • 输出结果:将收集到的叶节点编号按顺序输出,确保格式正确。
  • 这个方法确保了我们能够正确地构建二叉树,并按要求输出所有叶节点的编号。

    转载地址:http://jxaz.baihongyu.com/

    你可能感兴趣的文章
    nio 中channel和buffer的基本使用
    查看>>
    NIO基于UDP协议的网络编程
    查看>>
    NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
    查看>>
    Nitrux 3.8 发布!性能全面提升,带来非凡体验
    查看>>
    NI笔试——大数加法
    查看>>
    NLog 自定义字段 写入 oracle
    查看>>
    NLP 基于kashgari和BERT实现中文命名实体识别(NER)
    查看>>
    NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
    查看>>
    NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
    查看>>
    NLP学习笔记:使用 Python 进行NLTK
    查看>>
    NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
    查看>>
    NLP:使用 SciKit Learn 的文本矢量化方法
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>