int dbHelp(TreeNode *r,int &res)
{
if(!r)return 0;
int lh=dbHelp(r->left,res)+1;
int rh=dbHelp(r->right,res)+1;
res=max(res,lh+rh-2);
return max(lh,rh);
}
int diameterOfBinaryTree(TreeNode* root)
{
int res=0;
dbHelp(root,res);
return res;
}
[LeetCode] 543. Diameter of Binary Tree
二叉树直径算法解析
最新推荐文章于 2025-11-08 21:20:13 发布
本文介绍了一种求解二叉树直径的有效算法。通过递归遍历节点并记录路径长度,可以找到二叉树中最长路径的长度。此算法采用自底向上的方式计算每个节点的最长路径。
415

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



