★543. 二叉树的直径

543. 二叉树的直径

简单题,确实不难。

相当于就是求节点的深度。左孩子的最大深度 + 右孩子的最大深度 + 1 = 根节点深度。

本题要求的就是路径数,这里的路径数 = 节点数 - 1,然后想一下,对于一个节点来说,以他为根左右两边两边最长路径就是左孩子深度 + 右孩子深度。(这里的路径等于根节点深度 - 1嘛)

所以就是跑一个求深度的递归,然后每次都更新一下以当前节点为根的左右孩子深度和。

这个左右孩子的深度和就是所要求的路径长度。再 + 1 就是经过的节点个数,即以当前节点为根的深度。

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 max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        depth(root);
        return max;
    }
    public int depth(TreeNode root){
        if(root == null) return 0;
        int left = depth(root.left);
        int right = depth(root.right);
        if(max < left + right)      //这里这个max就是不加上根节点的节点个数,也等于路径个数。
            max = left + right;
        return Math.max(left, right) + 1;
    }
}
相关推荐
玖玥拾13 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
Hi李耶14 小时前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
白白白小纯19 小时前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
zander25820 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
yyds_yyd_1008621 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
lueluelue471 天前
LeetCode:链表
算法·leetcode·链表
橘子汽水1681 天前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
Re.不晚1 天前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
青山木2 天前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
星轨初途2 天前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode