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

    你可能感兴趣的文章
    mysql5.7安装
    查看>>
    mysql5.7性能调优my.ini
    查看>>
    MySQL5.7新增Performance Schema表
    查看>>
    Mysql5.7深入学习 1.MySQL 5.7 中的新增功能
    查看>>
    Webpack 之 basic chunk graph
    查看>>
    Mysql5.7版本单机版my.cnf配置文件
    查看>>
    mysql5.7的安装和Navicat的安装
    查看>>
    mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
    查看>>
    Mysql8 数据库安装及主从配置 | Spring Cloud 2
    查看>>
    mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
    查看>>
    MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
    查看>>
    MYSQL8.0以上忘记root密码
    查看>>
    Mysql8.0以上重置初始密码的方法
    查看>>
    mysql8.0新特性-自增变量的持久化
    查看>>
    Mysql8.0注意url变更写法
    查看>>
    Mysql8.0的特性
    查看>>
    MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
    查看>>
    MySQL8修改密码的方法
    查看>>
    Mysql8在Centos上安装后忘记root密码如何重新设置
    查看>>
    Mysql8在Windows上离线安装时忘记root密码
    查看>>