题解 | #二叉树的最大深度#

二叉树的最大深度

http://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73

使用递归的方法用下层递归返回的数字加上当前层的1,因为递归左边右边深度大小不同,我们使用Math.max 比较两边哪边深度大就使用哪个数值。另外还有一种思路就是求层序遍历,求出层序遍历,那么层序遍历返回的数组就是二叉树的深度

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型
  */
function maxDepth( root ) {
   const dis =  computed(root);
    return dis;
}
function computed(root){
    if(!root)return 0;
    let left = computed(root.left);
    let right = computed(root.right);
    return Math.max(left + 1,right +1);
}
module.exports = {
    maxDepth : maxDepth
};
全部评论

相关推荐

暮雨轻歌:看起来hr不能接受我菜查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务