![19083 二叉树的最长路径,第1张 19083 二叉树的最长路径,第1张](/aiimages/19083+%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E9%95%BF%E8%B7%AF%E5%BE%84.png)
19083 二叉树的最长路径
时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 编程题 语言: 不限定
Des
cription
二叉树中,任意两个节点间都存在一条唯一的路径,请求出所有路径中最长的路径长度。
输入格式
第一行为一个整数n,表示结点个数,结点以数字编号,根节点为1。
n<10
第二行为一个数字和#号组成的字符串,采用完全二叉树的存储形式,#表示空树。
输出格式
输出所有路径中最长的路径长度
输入样例
5
1234##5
输出样例
4
提示
样例最长路径为(4,5),路径长度为4
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
改良:
#include //ASI
using namespace std;
int n,ans=0;
string s;
int dfs(int r)
{
if(s[r-1]=='#'||r>s.size())/**< 空树,高度0 */
return 0;
int lhigh=dfs(2*r),rhigh=dfs(2*r+1);
ans=max(ans,lhigh+rhigh);/**< 此题目是枚举公共祖先,以r为公共祖先的最大距离为两子树高度和 */
return max(lhigh,rhigh)+1;/**< 返回树r高度 */
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0);
int i,j;
cin>>n>>s;
dfs(1);
cout<
评论列表(0条)