算法(TS):二叉树的最大深度

给定一个二叉树 root ,返回其最大深度。二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

上图二叉树的最大深度是3

解法一

使用递归。二叉树的最大深度是其左右子树的最大深度的最大值加一。

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 maxDepth(root: TreeNode | null): number {
    return root === null ? 0: Math.max(maxDepth(root.left),maxDepth(root.right)) + 1
    
};

时间复杂度O(n),空间复杂度O(hight),其中hight复杂度取决于树的高度,递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。

解法二

广度优先遍历。用 depth 保存树的深度,初始值为 0,用一个队列 nodeList 维护树中当前层的全部节点,进入下一层时,上一层的节点已经从队列的全部取出,并且将 depth ++。

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 maxDepth(root: TreeNode | null): number {
    if (!root) return 0
    let depth = 0
    const nodeList = [root]
    while(nodeList.length) {
        let size = nodeList.length
        while(size>0) {
            const node = nodeList.shift()
            if(node.right) {
                nodeList.push(node.right)
            }

            if(node.left) {
                nodeList.push(node.left)
            }
            size--
        }
        depth++ 
    }
    return depth
};

时间复杂度O(n),空间复杂度取决于队列存储的元素数量,在最坏情况下会达到 O(n)。

相关推荐
c#上位机6 小时前
halcon图像去噪—均值滤波
图像处理·算法·均值算法·halcon
曾几何时`7 小时前
347. 前 K 个高频元素 分别使用sort和priority_queue 对哈希结构自定义排序
算法
小李小李快乐不已7 小时前
图论理论基础(3)
数据结构·c++·算法·图论
牙牙要健康7 小时前
【open3d】示例:自动计算点人脸点云模型面部朝向算法
人工智能·python·算法
youngee117 小时前
hot100-41二叉搜索树中第K小的元素
算法
mmz12077 小时前
双指针问题5(c++)
c++·算法
星空露珠7 小时前
lua获取随机颜色rgb转换hex
数据结构·数据库·算法·游戏·lua
mit6.8248 小时前
预hash|vector<int> dfs
算法
Zsy_0510038 小时前
【数据结构】堆简单介绍、C语言实现堆和堆排序
c语言·数据结构·算法