数据结构与算法之二叉树: LeetCode 543. 二叉树的直径 (Ts版)

二叉树的直径

描述

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

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

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

示例 1

复制代码
输入:root = [1,2,3,4,5]
输出:3

解释:3 ,取路径 [4,2,1,3] 或 [5,2,1,3] 的长度。

示例 2

复制代码
输入:root = [1,2]
输出:1

提示

  • 树中节点数目在范围 [1, 1 0 4 10^4 104] 内
  • -100 <= Node.val <= 100

Typescript 版算法实现

1 ) 方案1:深度优先搜索

ts 复制代码
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function diameterOfBinaryTree(root: TreeNode | null): number {
    if (!root) return 0; // 如果树为空,返回 0
    if (!root.left && !root.right) return 0; // 如果树只有一个节点,也返回 0
 
    let ans = 0; // 注意这里初始化为 0 而不是 1,因为我们关心的是边的数量
 
    function depth(node: TreeNode | null): number {
        if (!node) return 0;
 
        const leftDepth = depth(node.left);
        const rightDepth = depth(node.right);

        ans = Math.max(ans, leftDepth + rightDepth);

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

2 ) 方案2:

ts 复制代码
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function diameterOfBinaryTree(root: TreeNode | null): number {
  let len=0
  function dfs(root) {
    if(!root) return 0
    let left = dfs(root.left)
    let right = dfs(root.right)
    len = Math.max(len,left+right)
    return Math.max(left,right)+1
  }
  dfs(root)
  return len
};
相关推荐
A尘埃5 小时前
保险公司车险理赔欺诈检测(随机森林)
算法·随机森林·机器学习
大江东去浪淘尽千古风流人物5 小时前
【VLN】VLN(Vision-and-Language Navigation视觉语言导航)算法本质,范式难点及解决方向(1)
人工智能·python·算法
努力学算法的蒟蒻6 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495646 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
AC赳赳老秦6 小时前
2026国产算力新周期:DeepSeek实战适配英伟达H200,引领大模型训练效率跃升
大数据·前端·人工智能·算法·tidb·memcache·deepseek
2401_841495646 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
budingxiaomoli6 小时前
优选算法-字符串
算法
我是咸鱼不闲呀7 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
qq7422349847 小时前
APS系统与OR-Tools完全指南:智能排产与优化算法实战解析
人工智能·算法·工业·aps·排程
A尘埃7 小时前
超市购物篮关联分析与货架优化(Apriori算法)
算法