数据结构与算法之二叉树: 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
};
相关推荐
米粒119 小时前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
Fuxiao___19 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
Mr_Xuhhh20 小时前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
漫随流水20 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
穿条秋裤到处跑21 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
CoovallyAIHub1 天前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github
CoovallyAIHub1 天前
低空安全刚需!西工大UAV-DETR反无人机小目标检测,参数减少40%,mAP50:95提升6.6个百分点
算法·架构·github
CoovallyAIHub1 天前
IEEE Sensors | 湖南大学提出KGP-YOLO:先定位风电叶片再检测缺陷,三数据集mAP均超87%
算法
Yupureki1 天前
《算法竞赛从入门到国奖》算法基础:动态规划-路径dp
数据结构·c++·算法·动态规划
副露のmagic1 天前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展