23 Maximum Depth of Binary Tree 二叉树最大深度

93 阅读1分钟

104. Maximum Depth of Binary Tree

最大深度指的是一条路径上最长节点数

解题思路

  1. 首先判断空节点直接返回 0
  2. 如果存在左节点则将数据 传递下去,通过 Math.max(left, right) + 1 左右节点剪枝选择maxDepth
  3. 最后自底而上一层层将数据归上去得到最终解

代码

/**
 * 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 === null) return 0
    let left = maxDepth(root.left)
    let right = maxDepth(root.right)
    return Math.max(left, right) + 1

};