【二叉树】Leetcode 543. 二叉树的直径【简单】

二叉树的直径

给你一棵二叉树的根节点,返回该树的 直径 。

二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。

两节点之间路径的 长度 由它们之间边数表示。

示例1:

输入:root = 1,2,3,4,5

输出:3

解释:3 ,取路径 4,2,1,35,2,1,3 的长度。

解题步骤

  • 1、定义一个递归函数,用于计算以当前节点为根节点的二叉树的最大深度。
  • 2、对于每个节点,计算其左子树的最大深度和右子树的最大深度,并将其相加得到经过该节点的路径长度。
  • 3、更新全局变量maxDiameter,记录经过每个节点的最长路径长度。
  • 4、递归遍历所有节点,更新maxDiameter。
  • 5、最终maxDiameter即为二叉树的直径

Java实现

java 复制代码
public class DiameterOfBinaryTree {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int val) {
            this.val = val;
        }
    }

    int diameter = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        calculateDiameter(root);
        return diameter;
    }

    private int calculateDiameter(TreeNode node) {
        if (node == null) {
            return 0;
        }

        // 递归计算左子树和右子树的深度
        int leftDepth = calculateDiameter(node.left);
        int rightDepth = calculateDiameter(node.right);

        // 更新直径,为左右子树深度之和的最大值
        diameter = Math.max(diameter, leftDepth + rightDepth);

        // 返回当前节点的深度
        return Math.max(leftDepth, rightDepth) + 1;
    }

    // 测试实例
    public static void main(String[] args) {
        // 构造二叉树:         1
        //                  /    \
        //                 2      3
        //                / \
        //               4   5
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);

        // 创建 DiameterOfBinaryTree 实例
        DiameterOfBinaryTree diameterCalculator = new DiameterOfBinaryTree();

        // 计算直径
        int result = diameterCalculator.diameterOfBinaryTree(root);
        System.out.println("二叉树的直径为: " + result);
    }
}

时间空间复杂度

  • 时间复杂度:O(n),其中n是二叉树中的节点数,每个节点都需要访问一次。
  • 空间复杂度:O(height),其中height是二叉树的高度,递归调用栈的深度。
相关推荐
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2122 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack202 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树2 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2123 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2123 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术3 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦3 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050734 天前
(一)小红的数组操作
算法·编程语言