【LeetCode 0104】【递归/分治】二叉树的最大深度

  1. Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:

**Input:** root = [3,9,20,null,null,15,7]
**Output:** 3

Example 2:

**Input:** root = [1,null,2]
**Output:** 2

Constraints:

  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100
Idea
分治递归:
分别算出左子树最大深度 和 右子树最大深度
返回 1+左右子树的最大深度
JavaScript Solution
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    
    if(!root){
        return 0
    }
    return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
};

相关推荐

  1. LeetCode104 深度

    2024-07-14 08:56:03       36 阅读
  2. [leetcode] 104. 深度

    2024-07-14 08:56:03       42 阅读
  3. LeetCode104.深度

    2024-07-14 08:56:03       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 08:56:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 08:56:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 08:56:03       57 阅读
  4. Python语言-面向对象

    2024-07-14 08:56:03       68 阅读

热门阅读

  1. CSS 样式缓存不更新

    2024-07-14 08:56:03       24 阅读
  2. 基于go-zero二次开发的脚本

    2024-07-14 08:56:03       20 阅读
  3. RabbitMQ的工作模式

    2024-07-14 08:56:03       17 阅读
  4. 跨域问题出现的原因,怎么解决?

    2024-07-14 08:56:03       21 阅读
  5. Isaac sim中使用不同的backone

    2024-07-14 08:56:03       17 阅读
  6. Python中的pytest的使用

    2024-07-14 08:56:03       26 阅读
  7. Power BI 工具介绍

    2024-07-14 08:56:03       24 阅读
  8. 【C语言】多线程服务器

    2024-07-14 08:56:03       22 阅读
  9. 数学建模如何创新

    2024-07-14 08:56:03       27 阅读