LeetCode:543二叉树的直径

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    //全局变量,记录直径
    int maxDiameter = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        getDepth(root);
        return maxDiameter;    
    }
    //返回当前以node为根的子树的最大深度
    private int getDepth(TreeNode node){
        if(node == null){
            return 0;
        }
        //左右子树的深度
        int leftDepth = getDepth(node.left);
        int rightDepth = getDepth(node.right);
        //记算最大直径
        maxDiameter = Math.max(maxDiameter,leftDepth + rightDepth);

        return Math.max(leftDepth , rightDepth) + 1;
    }
}

路径可能不经过root节点,也就是说可能只在一边,所以不能直接只去计算左子树深度+右子树深度。

所以对于每个节点都要计算出它的左子树+右子树的深度

相关推荐
启观川12 小时前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·笔记·python·算法
码爸12 小时前
排序算法介绍
python·算法·排序算法
Interview Aid11213 小时前
SoFi 面试流程全解析:技术面试、OA 与备考指南
面试·职场和发展
动词ing13 小时前
【题目练习】算法 组合总和||
算法
longlongzihan14 小时前
链表找环:Floyd 判圈算法(LeetCode 141 & 142 )
c++·算法·leetcode·链表
专业程序开发源14 小时前
flask家电故障预测系统92491-计算机课程设计/毕业设计
vscode·python·sql·算法·flask·课程设计
Logic10114 小时前
C语言/数据结构欧几里得算法题解:长方形切割最大正方形——贪心划分计数
c语言·数据结构·算法·贪心算法·时间复杂度·空间复杂度·欧几里得算法
yi01114 小时前
LeetCode 643. 子数组最大平均数 I|从暴力枚举到滑动窗口
人工智能·笔记·python·算法·leetcode·滑动窗口
YangYang9YangYan15 小时前
2027数学与应用数学转产品经理:面试解释与项目准备
面试·职场和发展·产品经理
极光通讯15 小时前
服务器内存来料检验(IQC)实操:批次追溯、外观判定与上机验证
java·服务器·算法