【二叉树】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是二叉树的高度,递归调用栈的深度。
相关推荐
专注前端30年15 分钟前
智能物流路径规划系统:核心算法实战详解
算法
json{shen:"jing"}33 分钟前
字符串中的第一个唯一字符
算法·leetcode·职场和发展
追随者永远是胜利者1 小时前
(LeetCode-Hot100)15. 三数之和
java·算法·leetcode·职场和发展·go
程序员酥皮蛋2 小时前
hot 100 第二十七题 27.合并两个有序链表
数据结构·leetcode·链表
BlockWay2 小时前
西甲赛程搬进平台:WEEX以竞猜开启区域合作落地
大数据·人工智能·算法·安全
im_AMBER3 小时前
Leetcode 121 翻转二叉树 | 二叉树中的最大路径和
数据结构·学习·算法·leetcode
mit6.8244 小时前
二分+贪心
算法
programhelp_5 小时前
特斯拉 MLE 超详细面经 + 避坑
数据结构·人工智能·算法·面试·职场和发展
越甲八千5 小时前
深入了解迭代器erase()之后的失效逻辑
算法
躺柒5 小时前
读人工智能全球格局:未来趋势与中国位势06人类的未来(下)
大数据·人工智能·算法·ai·智能