LeetCode:剑指 Offer 55 - I. 二叉树的深度
发布日期:2022-09-10 02:24:22
浏览次数:8
分类:技术文章
本文共 589 字,大约阅读时间需要 1 分钟。
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
提示:
- 节点总数 <= 10000
注意:本题与主站 104 题相同:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
解题思路
1.使用递归,返回左子树高度和右子树高度的最大值+1
代码
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * @param {TreeNode} root * @return {number} */var maxDepth = function(root) { if (!root) return 0; return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;};
转载地址:https://blog.csdn.net/Bertil/article/details/124815021 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
关注你微信了!
[***.104.42.241]2024年03月25日 03时24分33秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!