104. Maximum Depth of Binary Tree
最大深度指的是一条路径上最长节点数
解题思路
- 首先判断空节点直接返回 0
- 如果存在左节点则将数据 传递下去,通过
Math.max(left, right) + 1左右节点剪枝选择maxDepth - 最后自底而上一层层将数据归上去得到最终解
代码
/**
* 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
};