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;
}