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

本文共 1960 字,大约阅读时间需要 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/

    你可能感兴趣的文章
    OA项目之我的审批(会议查询&会议签字)
    查看>>
    OA项目之项目简介&会议发布
    查看>>
    ObjC的复制操作
    查看>>
    Object c将一个double值转换为时间格式
    查看>>
    object detection之Win10配置
    查看>>
    object detection训练自己数据
    查看>>
    object detection错误Message type "object_detection.protos.SsdFeatureExtractor" has no field named "bat
    查看>>
    object detection错误之Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
    查看>>
    object detection错误之no module named nets
    查看>>
    Object of type 'ndarray' is not JSON serializable
    查看>>
    Object Oriented Programming in JavaScript
    查看>>
    object references an unsaved transient instance - save the transient instance before flushing
    查看>>
    Object 类的常见方法有哪些?
    查看>>
    Object-c动态特性
    查看>>
    Object.assign用法
    查看>>
    Object.create
    查看>>
    Object.defineProperty详解
    查看>>
    Object.keys()的详解和用法
    查看>>
    objectForKey与valueForKey在NSDictionary中的差异
    查看>>
    Objective - C 小谈:消息机制的原理与使用
    查看>>