博客
关于我
【树的应用】——列出叶结点 (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/

    你可能感兴趣的文章
    Python 循环异或对文件进行加解密
    查看>>
    Python开发环境搭建(附VMware安装包及虚拟机环境)
    查看>>
    python 微信扫码登录_python实现微信第三方网站扫码登录(Django)
    查看>>
    Python 快速下载依赖
    查看>>
    python实现非参数统计的Cochran检验 (附完整源码)
    查看>>
    python 怎么验证是否安装成功 scrapy
    查看>>
    Python 手写数字识别-1
    查看>>
    Python实现接口自动化测试库(JSON与Requests)详解
    查看>>
    Python 手写数字识别-3-sklearn中的几种算法
    查看>>
    python实现SSIM和MSSSIM计算 (附完整源码)
    查看>>
    Python 打开文件注意事项
    查看>>
    python 批量修改文件名_python windows下批量修改文件名
    查看>>
    Python 抓取网页乱码问题 以及EXCEL乱码
    查看>>
    python 抓取网页内容
    查看>>
    python 按照当前日期创建文件
    查看>>
    Python 接口并发测试详解
    查看>>
    Python 接口自动化 —— requests框架
    查看>>
    python 接口自动化数据结构(如列表、字典、元组)
    查看>>
    Python 接口自动化测试中的深拷贝与浅拷贝~
    查看>>
    Python 接口自动化测试中的高阶函数
    查看>>