0104-Easy-二叉树的最大深度
题目
3
/ \
9 20
/ \
15 7解法
解法一:递归
/**
* 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) {
// 根为空,终止条件
if (root == null) {
return 0;
}
// 当前根的最大深度,则需要取左节点最大深度与右节点最大深度的最大值,然后 + 1
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}最后更新于