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

二叉树的直径

描述

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

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

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

示例 1

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

解释:3 ,取路径 4,2,1,35,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
};
相关推荐
youngerwang37 分钟前
【从搬运工到协处理器:网卡芯片架构、算法、验证与边缘演进深度剖析】
网络·算法·架构·芯片
KaMeidebaby1 小时前
卡梅德生物技术快报|纯化重组蛋白实操详解
人工智能·python·tcp/ip·算法·机器学习
手写码匠2 小时前
从零实现 Prompt 工程引擎:结构化提示、自动优化与多轮自省体系
人工智能·深度学习·算法·aigc
无限码力2 小时前
阿里算法岗 0530笔试真题 - 多约束条件下的元素匹配统计
算法·阿里笔试真题·阿里机试真题·阿里算法岗笔试
lqqjuly2 小时前
MLA — 多头潜在注意力深度解析
深度学习·神经网络·算法
吴可可1233 小时前
SolidWorks草图转三维DWG技巧
算法
redaijufeng3 小时前
C++雾中风景7:闭包
c++·算法·风景
小欣加油4 小时前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
尽兴-4 小时前
2.1 向量基础:Embedding、余弦相似度、欧氏距离、向量检索
算法·embedding·欧氏距离·向量检索·余弦相似度
Black蜡笔小新4 小时前
自动化AI算法训练服务器DLTM训推一体工作站赋能多行业智能化升级
人工智能·算法·自动化