栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

二叉树的最长路径问题|PTA|C++

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树的最长路径问题|PTA|C++

1.二叉树的最长路径问题()


函数接口

template 
int LongestPathInBinaryTree(BinNode* root, int& max_dist);

裁判测试程序样例

#include 

template 
class BinNode{
    public:
        virtual ~BinNode() {}
        virtual BinNode* left() const = 0; //返回左子树的根位置
        virtual BinNode* right() const = 0; //返回右子树的根位置
        virtual bool isLeaf() = 0;
}; //二叉树节点

template 
BinNode* constructBinTree(const int N);
//生成N个节点的二叉树,返回根位置(过程省略)

template 
int LongestPathInBinaryTree(BinNode* root, int& max_dist);

int main()
{
  int N; //节点数量
    ...
  BinNode root = constructBinTree(N);

  int max_dist = 0;    //最长路径长度的初始值
  LongestPathInBinaryTree(root, max_dist);  //寻找最长路径
  cout << max_dist << endl;      //输出最长路径的长度
   ...
  return 0;

}


输入样例:

7
9 7 5 19 11 13 21

输出样例

5
1.1AC代码
int res=0;
template
int getHeight(BinNode* root){
    if(!root)
        return 0;
    int left=getHeight(root->left());
    int right=getHeight(root->right());

    res=max(res,left+right);
    return 1+max(left,right);
}
template
int LongestPathInBinaryTree(BinNode* root, int& max_dist){
    if(!root)
        return 0;
    getHeight(root);
    max_dist=res;
    return res;

1.2分析过程

22 二叉树的最长的路径长度和最大路径和

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/312116.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号