数据结构与算法之二叉树: 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
};
相关推荐
CoovallyAIHub3 分钟前
YOLOv13都来了,目标检测还卷得动吗?别急,还有这些新方向!
深度学习·算法·计算机视觉
转转技术团队36 分钟前
边学边做:图片识别技术的学习与应用
后端·算法
一块plus1 小时前
2025 年值得一玩的最佳 Web3 游戏
算法·设计模式·程序员
前端拿破轮1 小时前
不是吧不是吧,leetcode第一题我就做不出来?😭😭😭
后端·算法·leetcode
一块plus1 小时前
什么是去中心化 AI?区块链驱动智能的初学者指南
人工智能·后端·算法
Mr_Xuhhh1 小时前
网络基础(1)
c语言·开发语言·网络·c++·qt·算法
前端拿破轮1 小时前
😭😭😭看到这个快乐数10s,我就知道快乐不属于我了🤪
算法·leetcode·typescript
lyx 弈心1 小时前
I/O 进程 7.2
linux·算法·io
静心问道1 小时前
APE:大语言模型具有人类水平的提示工程能力
人工智能·算法·语言模型·大模型
醇醛酸醚酮酯2 小时前
std::promise和std::future的使用示例——单线程多链接、多线程单链接
网络·c++·算法