二叉树问题
洛谷P3884
Hi~ 今天这这么早就更新题解啦~ 今天继续来看一到二叉树的问题


这道题主要分为三部分:求宽度 求深度 求距离
求宽度和求深度其实可以合起来 所以就变成了两部分
Part 1 – 宽度&深度
void get_node_depth(int root,int d) // 传根结点&当前结点深度
{
if (root==0) // 如果根结点=0 返回
return;
dep[root]=d; // 一个数组记录这个结点的深度
cnt[d]++; // 一个数组记录当前这个深度有多少个结点
depth=max(depth,d); // 看看是我们记录深度的变量大 还是当前的深度大 并记录
width=max(width,cnt[d]); // 记录当前宽度和宽度变量中大的那个
if (l[root]==0 && r[root]==0) // 如果l或r没有root了就返回
return ;
get_node_depth(l[root],d+1); // 遍历左孩子
get_node_depth(r[root],d+1); // 遍历右孩子
}
Part 2 – 求距离
int ul=0,vl=0; // 记u移动的距离和l移动的距离
while (dep[u]>dep[v]) // 如果u>v
{
ul++; // u移动距离++
u=f[u]; // u等于u的父结点
}
while (dep[u]<dep[v]) // 同理 不在做解释
{
vl++;
v=f[v];
}
while (u!=v) // 如果u还不等于v
{
u=f[u]; // u等于u的父结点
v=f[v]; // v等于v的父结点
ul++; // 距离们++
vl++;
}
好吧 这样看着可能有点乱 所以完整代码在这里
//
// main.cpp
// 二叉树问题
//
// Created by Helen on 2020/8/7.
// Copyright © 2020 Helen. All rights reserved.
//
#include <iostream>
using namespace std;
const int N=1000005;
int n,u,v,width,depth;
int l[N],r[N],f[N],dep[N],cnt[N];
void get_node_depth(int root,int d);
int main ()
{
cin >> n;
int x,y;
for (int i=1;i<n;i++)
{
cin >> x >> y;
if (l[x]) r[x]=y;
else l[x]=y;
f[y]=x;
}
cin >> u >> v;
get_node_depth(1,1);
int ul=0,vl=0;
while (dep[u]>dep[v])
{
ul++;
u=f[u];
}
while (dep[u]<dep[v])
{
vl++;
v=f[v];
}
while (u!=v)
{
u=f[u];
v=f[v];
ul++;
vl++;
}
cout << depth << endl << width << endl;
cout << ul*2+vl << endl;
return 0;
}
void get_node_depth(int root,int d)
{
if (root==0)
return;
dep[root]=d;
cnt[d]++;
depth=max(depth,d);
width=max(width,cnt[d]);
if (l[root]==0 && r[root]==0)
return ;
get_node_depth(l[root],d+1);
get_node_depth(r[root],d+1);
}
----------------------------------------✂︎---------------------------------------------
此题解已经AC 欢迎指出更多优化方法~
这篇博客详细介绍了洛谷P3884二叉树问题,包括二叉树的宽度和深度计算,以及节点间的距离求解。作者将问题分解为两部分:宽度和深度的综合处理,以及单独的距离计算。博客提供了完整的代码实现,并邀请读者分享优化方案。
852

被折叠的 条评论
为什么被折叠?



