题目描述:
链接: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/submissions/
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
代码:
和求最小深度一样, 利用递归思想
class Solution {
// T: O(n), S: O(n)
public int maxDepth(TreeNode root) {
if (root == null) return 0;
// 返回当前节点的深度1
if ((root.left == null) && (root.right == null)) return 1;
int max_depth = Integer.MIN_VALUE;
// 获取左右子树中的较大深度
if (root.left != null) {
max_depth = Math.max(max_depth, maxDepth(root.left));
}
if (root.right != null) {
max_depth = Math.max(max_depth, maxDepth(root.right));
}
return max_depth + 1;
}
}
京公网安备 11010502036488号