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

二叉树的直径

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

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

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

示例1:

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

输出:3

解释:3 ,取路径 [4,2,1,3] 或 [5,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是二叉树的高度,递归调用栈的深度。
相关推荐
期末考复习中,蓝桥杯都没时间学了17 分钟前
力扣刷题19
算法·leetcode·职场和发展
Renhao-Wan25 分钟前
Java 算法实践(四):链表核心题型
java·数据结构·算法·链表
踩坑记录1 小时前
递归回溯本质
leetcode
zmzb01031 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
好学且牛逼的马2 小时前
【Hot100|25-LeetCode 142. 环形链表 II - 完整解法详解】
算法·leetcode·链表
H Corey2 小时前
数据结构与算法:高效编程的核心
java·开发语言·数据结构·算法
SmartBrain3 小时前
Python 特性(第一部分):知识点讲解(含示例)
开发语言·人工智能·python·算法
01二进制代码漫游日记3 小时前
自定义类型:联合和枚举(一)
c语言·开发语言·学习·算法
小学卷王3 小时前
复试day25
算法
样例过了就是过了4 小时前
LeetCode热题100 和为 K 的子数组
数据结构·算法·leetcode