博客
关于我
18924 二叉树的宽度
阅读量:798 次
发布时间:2023-04-04

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

二叉树的宽度是指具有节点数目最多的那一层的节点个数。我们需要通过给定的父节点关系,构建二叉树并计算其宽度。

输入格式

输入共有n行:

  • 第一行是一个整数n,表示有n个结点,编号为1至n,结点1为树根。
  • 接下来的n-1行,每行有两个整数x和y,表示在二叉树中x为y的父节点。第一次出现的x,其y为左孩子;若x已经有左孩子,则y为右孩子。

输出格式

输出二叉树的宽度。

思路

  • 构建二叉树结构:使用数组来表示每个节点的左孩子和右孩子。
  • 广度优先搜索(BFS):通过队列实现层序遍历,记录每一层的节点数。
  • 统计最大宽度:在遍历过程中,跟踪每一层的节点数,找出最大的那个数作为宽度。
  • 代码

    #include 
    #include
    using namespace std;
    int bfs(vector
    &children, int n) {
    vector
    nodeQueue;
    nodeQueue.push_back(1); // 根节点1
    int maxLevelWidth = 0;
    int currentLevelSize = 1;
    while (!nodeQueue.empty()) {
    int nextLevelSize = 0;
    for (int i = 0; i < currentLevelSize; ++i) {
    int current = nodeQueue[i];
    if (children[current] == 0) {
    // 左孩子未存在,存为左孩子
    children[current] = ++lastNodeID;
    nextLevelSize++;
    } else if (children[current] != 0) {
    // 已经有左孩子,存为右孩子
    children[current] = ++lastNodeID;
    nextLevelSize++;
    }
    // 检查是否是最后一个节点,避免超出数组大小
    if (children[current] > n) {
    children[current] = 0;
    }
    }
    if (nextLevelSize > maxLevelWidth) {
    maxLevelWidth = nextLevelSize;
    }
    nodeQueue.clear();
    nodeQueue.insert(nodeQueue.end(), nextLevelSize, children);
    currentLevelSize = nextLevelSize;
    }
    return maxLevelWidth;
    }
    int main() {
    vector
    children(n + 1, 0); // children[0]不使用
    int lastNodeID = 1;
    int n;
    cin >> n;
    for (int i = 1; i < n; ++i) {
    int x, y;
    cin >> x >> y;
    if (children[x] == 0) {
    children[x] = y;
    lastNodeID = y;
    } else {
    children[x] = y;
    lastNodeID = y;
    }
    }
    int width = bfs(children, n);
    cout << width << endl;
    return 0;
    }

    代码解释

  • 构建二叉树:使用数组children存储每个节点的左、右孩子。初始时,所有节点的左、右孩子都为0。
  • 广度优先搜索:使用队列nodeQueue进行层序遍历。每次从队列头部取出一个节点,检查其左、右孩子是否存在。如果存在,根据规则存入左、右孩子,并将新节点加入队列。
  • 统计宽度:在每一层遍历完所有节点后,记录当前层的节点数。如果当前层的节点数大于已知的最大宽度,则更新最大宽度。
  • 输出结果:遍历结束后,输出最大宽度,即二叉树的宽度。
  • 转载地址:http://csrfk.baihongyu.com/

    你可能感兴趣的文章
    multiprocessing.Pool:map_async 和 imap 有什么区别?
    查看>>
    MySQL Connector/Net 句柄泄露
    查看>>
    multiprocessor(中)
    查看>>
    mysql CPU使用率过高的一次处理经历
    查看>>
    Multisim中555定时器使用技巧
    查看>>
    MySQL CRUD 数据表基础操作实战
    查看>>
    multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
    查看>>
    mysql csv import meets charset
    查看>>
    multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
    查看>>
    MySQL DBA 数据库优化策略
    查看>>
    multi_index_container
    查看>>
    mutiplemap 总结
    查看>>
    MySQL Error Handling in Stored Procedures---转载
    查看>>
    MVC 区域功能
    查看>>
    MySQL FEDERATED 提示
    查看>>
    mysql generic安装_MySQL 5.6 Generic Binary安装与配置_MySQL
    查看>>
    Mysql group by
    查看>>
    MySQL I 有福啦,窗口函数大大提高了取数的效率!
    查看>>
    mysql id自动增长 初始值 Mysql重置auto_increment初始值
    查看>>
    MySQL in 太多过慢的 3 种解决方案
    查看>>