数据结构与算法之二叉树: 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
};
相关推荐
阿巴~阿巴~24 分钟前
蓝桥杯速成刷题清单(上)
c语言·c++·算法·蓝桥杯
drylong32 分钟前
困难 - 2999. 统计强大整数的数目
算法
小美爱刷题1 小时前
力扣DAY40-45 | 热100 | 二叉树:直径、层次遍历、有序数组->二叉搜索树、验证二叉搜索树、二叉搜索树中第K小的元素、右视图
数据结构·算法·leetcode
冷月半明1 小时前
Prophet预测波动性实战:5招让你的时间序列曲线"活"起来 破解预测曲线太平滑的行业痛点
后端·算法·机器学习
Ayanami_Reii1 小时前
NOIP2011提高组.玛雅游戏
算法·游戏·深度优先
熬夜造bug1 小时前
LeetCode Hot100 刷题笔记(2)—— 子串、普通数组、矩阵
笔记·leetcode·矩阵
_extraordinary_1 小时前
笔试专题(六)
算法·哈希算法·贪心·模拟·滑动窗口·构造
学习编程的gas2 小时前
数据结构——堆的实现和堆排序
数据结构·算法
claude62 小时前
实测文心4.5与X1一个月后,我预测文心大模型4.5 Turbo将有这几个升级点
算法
jz_ddk2 小时前
[实战]多天线空域抗干扰技术:原理、数学推导与工程仿真(完整仿真代码)
python·算法·毕业设计·信号处理