class Solution0 {
static int ans;
public int diameterOfBinaryTree(TreeNode root) {
if(root==null) return 0;
ans = 1;
depth(root);
return ans - 1;
}
public int depth(TreeNode node) {
if (node == null) {
return 0; // 访问到空节点了,返回0
}
int L = depth(node.left); // 左儿子为根的子树的深度
int R = depth(node.right); // 右儿子为根的子树的深度
ans = Math.max(ans, L+R+1); // 计算d_node即L+R+1 并更新ans
return Math.max(L, R) + 1; // 返回该节点为根的子树的深度
}
}
543. 二叉树的直径
最新推荐文章于 2025-11-24 14:44:53 发布
本文介绍了如何使用递归方法在二叉树中计算直径,即最长路径长度。通过`depth`函数实现左右子树深度的最大和加上根节点,展示了如何在`Solution0`类中计算树的直径。
875

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



