问题描述:
给定root
二叉树的 ,返回其最大深度。
二叉树的最大深度 是从根节点到最远叶节点的最长路径上的节点数。
示例:
思路:
找到左子树和右子树的最大深度取在大值,然后在+1即为该树的最大深度。
代码:
public class MaximumDepthOfBinaryTree {
public static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
}
// 以root为头的树,最大高度是多少返回!
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}