刷题顺序按照代码随想录建议
题目描述
英文版描述
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, 10(4)]. -100 <= Node.val <= 100
英文版地址
中文版描述
给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入: root = [3,9,20,null,null,15,7] 输出: 3
示例 2:
输入: root = [1,null,2] 输出: 2
提示:
- 树中节点的数量在
[0, 10^4]区间内。 -100 <= Node.val <= 100
中文版地址
解题方法
递归法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return recursion(root);
}
private int recursion(TreeNode root) {
if (root == null) {
return 0;
}
int l = recursion(root.left);
int r = recursion(root.right);
return Math.max(l, r) + 1;
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是二叉树的节点数,每一个节点恰好被遍历一次
- 空间复杂度:O(n),为递归过程中栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n)