543.二叉树的直径

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

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

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

java 复制代码
class Solution{
    // 全局变量
    int ans = 0;
    
    public int diameterOfBinaryTree(TreeNode root){
        heigh(root);
        return ans;
    }
    
    public int depth(TreeNode root){
        // 返回的为:root节点的左右子树中最大的树的节点数
        if(root == null) return 0;
        int l = depth(root.left);
        int r = depth(root.right);
        ans = Math.max(ans, l + r)
        return Math.max(l, r) + 1;
    }
}
相关推荐
小白菜又菜几秒前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
不想看见4041 分钟前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode
多恩Stone5 分钟前
【3D-AICG 系列-12】Trellis 2 的 Shape VAE 的设计细节 Sparse Residual Autoencoding Layer
人工智能·python·算法·3d·aigc
踢足球092918 分钟前
寒假打卡:2026-2-23
数据结构·算法
yzx99101340 分钟前
蓝桥杯备考智能体:构建高并发、智能化编程竞赛助手的深度实践
职场和发展·蓝桥杯
田里的水稻1 小时前
FA_建图和定位(ML)-超宽带(UWB)定位
人工智能·算法·数学建模·机器人·自动驾驶
Navigator_Z1 小时前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
郝学胜-神的一滴1 小时前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构
摸鱼仙人~1 小时前
算法题避坑指南:数组/循环范围的 `+1` 到底什么时候加?
算法
liliangcsdn1 小时前
基于似然比的显著图可解释性方法的探索
人工智能·算法·机器学习