SCAU18924--二叉树的宽度

 

18924 二叉树的宽度

时间限制:1000MS  代码长度限制:10KB
提交次数:0 通过次数:0

题型: 编程题   语言: G++;GCC

Description

二叉树的宽度指的是具有节点数目最多的那一层的节点个数。
          1
         / \
        2   3
       /     
      4     
答案为2, 第二层节点数最多,为2个节点。



 

输入格式

共n行。
第一行一个整数n,表示有n个结点,编号为1至n,结点1为树根。(1<=n<=50)
第二行至第n行,每行有两个整数x和y,表示在二叉树中x为y的父节点。x第一次出现时y为左孩子


 

输出格式

输出二叉树的宽度。


 

输入样例

5
1 2
1 3
2 4
2 5


 

输出样例

2
#include <iostream>     // 用于输入输出
#include <vector>       // 用于动态数组
#include <queue>        // 用于BFS队列
#include <algorithm>    // 用于 max 函数

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<int> lchild(n + 1, 0);     // 左孩子
    vector<int> rchild(n + 1, 0);     // 右孩子
    vector<int> appear(n + 1, 0);     // 记录每个节点作为父节点出现的次数

    for (int i = 1; i < n; ++i) {
        int x, y;
        cin >> x >> y;
        if (appear[x] == 0) {
            lchild[x] = y;  // 第一次出现是左孩子
        } else {
            rchild[x] = y;  // 第二次出现是右孩子
        }
        appear[x]++;
    }

    queue<pair<int, int>> q; // pair<节点编号, 所在层号>
    q.push({1, 1});          // 根节点为1,层号为1
    vector<int> count(n + 2, 0); // 每层节点数量

    while (!q.empty()) {
        int node = q.front().first;
        int depth = q.front().second;
        q.pop();

        count[depth]++;

        if (lchild[node]) {
            q.push({lchild[node], depth + 1});
        }
        if (rchild[node]) {
            q.push({rchild[node], depth + 1});
        }
    }

    // 取所有层中的最大宽度
    int max_width = 0;
    for (int i = 1; i <= n; ++i) {
        max_width = max(max_width, count[i]);
    }

    cout << max_width << "\n";

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值