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

二叉树的最大深度

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

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

/**
  * 
  * @param root TreeNode类 
  * @return int整型
  */
function maxDepth( root ) {
    // write code here
    if(!root) return 0;
    const left = maxDepth(root.left);
    const right = maxDepth(root.right);
    return left > right ? left + 1 : right + 1;
}
module.exports = {
    maxDepth : maxDepth
};

二叉树的题用递归解法会比较简单

求树的深度,节点有左右子树就取最大的那边+1

全部评论

相关推荐

点赞 评论 收藏
分享
02-28 01:18
已编辑
南昌大学 后端工程师
后测速成辅导一两个月...:把开源经历放个人项目上边应该更好,就像大部分人都把实习经历放个人项目上边
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务