[LeetCode] 104. Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100
二叉树的最大深度。
给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
思路
这是后序遍历的基础题,直接上代码。影子题 543。
复杂度
时间O(n)
空间O(h) - 树的高度
代码
Java实现
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int maxDepth(TreeNode root) { // corner case if (root == null) { return 0; } // normal case int leftMax = maxDepth(root.left); int rightMax = maxDepth(root.right); return Math.max(leftMax, rightMax) + 1; } }
相关题目
104. Maximum Depth of Binary Tree 110. Balanced Binary Tree 366. Find Leaves of Binary Tree 543. Diameter of Binary Tree 1522. Diameter of N-Ary Tree 1245. Tree Diameter
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步