博客
关于我
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/

    你可能感兴趣的文章
    Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
    查看>>
    Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
    查看>>
    Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
    查看>>
    Mysql 学习总结(89)—— Mysql 库表容量统计
    查看>>
    mysql 实现主从复制/主从同步
    查看>>
    mysql 审核_审核MySQL数据库上的登录
    查看>>
    mysql 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
    查看>>
    mysql 导入导出大文件
    查看>>
    mysql 将null转代为0
    查看>>
    mysql 常用
    查看>>
    MySQL 常用列类型
    查看>>
    mysql 常用命令
    查看>>
    Mysql 常见ALTER TABLE操作
    查看>>
    mysql 往字段后面加字符串
    查看>>
    mysql 快速自增假数据, 新增假数据,mysql自增假数据
    查看>>
    Mysql 报错 Field 'id' doesn't have a default value
    查看>>
    MySQL 报错:Duplicate entry 'xxx' for key 'UNIQ_XXXX'
    查看>>
    mysql 排序id_mysql如何按特定id排序
    查看>>
    Mysql 提示:Communication link failure
    查看>>
    mysql 插入是否成功_PDO mysql:如何知道插入是否成功
    查看>>