T236448 求二叉树中节点间的宽度
#include<cstdio>
#include<iostream>
using namespace std;
int n;
int fa[100],root[100],son[100];
int depth[100],width[100];
int lca(int x,int y)//求出两个结点的最顶端的根结点
{
if(x == y){
return x; //两个点如果相同,那么 LCA 就是它本身
}
else if(depth[x] == depth[y]){
return lca(fa[x],fa[y]); //如果两个点深度相同,就访问它们的父亲结点
}
else if(depth[x] < depth[y]){
return lca(x,fa[y]);//如果x的深度小于y的深度,就访问y的父亲结点,直到x y 深度相同
}
else{
return lca(fa[x],y);//如果y的深度小于x的深度,就访问x的父亲结点,直到x y 深度相同
}
}
int main(){
cin >> n;
depth[1] = 1;
for(int i = 1;i < n;i++)//注意这里循环是到n - 1,按照题目要求,前n - 1行才是需要的
{
cin >> root[i] >> son[i];
depth[son[i]] = depth[root[i]] + 1;//子结点的深度是父亲结点的深度 + 1
fa[son[i]] = root[i];//一个结点的父亲结点是它本身
}
int x,y;
cin >> x >> y;
int max_depth = 1; //用于记录深度
for(int i = 1;i <= n;i++)
{
max_depth = max(max_depth,depth[i]);//求出深度
width[depth[i]]++; //这里是为下一步做准备,再循环统计一次有点浪费
}
cout << max_depth << endl;//输出深度
int max_width = 1;
for(int i = 1;i <= n;i++)
{
max_width = max(max_width,width[i]);//求出宽度
}
cout << max_width << endl;//输出宽度
int k = lca(x,y); //求 LCA 的结点序号
cout << (depth[x] - depth[k]) * 2 + depth[y] - depth[k]; //求两个结点间距离
return 0;
}

浙公网安备 33010602011771号