104_二叉树的最大深度

78 阅读1分钟

题目描述

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

img

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

思路

递归

遍历左右子树,每次遍历对深度 + 1,节点为null时返回0

循环

对二叉树的每一层节点构造, 将节点和该节点的深度构造成一个对象进行入栈,然后对栈进行循环,每次出栈栈顶元素,如果该元素存在左右子树,将其子树和对应的深度加到栈中(子树的深度为节点深度+1),更新最大深度

复杂度分析

递归

  • 时间复杂度: O(n)
  • 空间复杂度: O(h) (h 为二叉树的高度)

循环

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

code

递归

var maxDepth = function (root) {
    if(!root) return 0
    let left = maxDepth(root.left) + 1
    let right = maxDepth(root.right) + 1
    return Math.max(left, root)
}

循环

var maxDepth = function (root) {
    const stack = [{node: root, depth: 1}]
    let maxDepth = 0
    while(stack.length > 0){
        const {node, depth} = stack.pop()
        if(node){
            maxDepth = Math.max(depth, maxDepth)
            stack.push({node: node.left, depth: depth + 1})
            stack.push({node: node.right, depth: depth + 1})
        }
    }
    return maxDepth
}