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

    你可能感兴趣的文章