https://leetcode.cn/problems/diameter-of-binary-tree/
给你一棵二叉树的根节点,返回该树的 直径 。
二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。
两节点之间路径的 长度 由它们之间边数表示。
示例 :

输入:root = [1,2,3,4,5] 输出:3 解释:3 ,取路径 [4,2,1,3] 或 [5,2,1,3] 的长度。
public class hot543 {
// 记录最大直径
private int maxDiameter = 0;
public int diameterOfBinaryTree(TreeNode root) {
maxDiameter = 0; // 重置
calculateDepth(root); // 计算深度并更新直径
return maxDiameter;
}
private int calculateDepth(TreeNode node) {
if (node == null) {
return 0;
}
// 递归计算左右子树的最大深度
int leftDepth = calculateDepth(node.left);
int rightDepth = calculateDepth(node.right);
// 经过当前节点的最长路径 = 左子树深度 + 右子树深度
maxDiameter = Math.max(maxDiameter, leftDepth + rightDepth);
// 返回以当前节点为根的子树的最大深度
return Math.max(leftDepth, rightDepth) + 1;
}
}
880

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



