算法(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)。

相关推荐
NAGNIP1 天前
一文搞懂机器学习中的特征降维!
算法·面试
NAGNIP1 天前
一文搞懂机器学习中的特征构造!
算法·面试
Learn Beyond Limits1 天前
解构语义:从词向量到神经分类|Decoding Semantics: Word Vectors and Neural Classification
人工智能·算法·机器学习·ai·分类·数据挖掘·nlp
你怎么知道我是队长1 天前
C语言---typedef
c语言·c++·算法
Qhumaing1 天前
C++学习:【PTA】数据结构 7-1 实验7-1(最小生成树-Prim算法)
c++·学习·算法
Z1Jxxx1 天前
01序列01序列
开发语言·c++·算法
汽车仪器仪表相关领域1 天前
全自动化精准检测,赋能高效年检——NHD-6108全自动远、近光检测仪项目实战分享
大数据·人工智能·功能测试·算法·安全·自动化·压力测试
Doro再努力1 天前
【数据结构08】队列实现及练习
数据结构·算法
刘一说1 天前
TypeScript 与 JavaScript:现代前端开发的双子星
javascript·ubuntu·typescript