求解二叉树的最大深度和最小深度
二叉树的最大深度
//给定一个二叉树,找出其最大深度。
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left) + 1, maxDepth(root.right) + 1);
}
二叉树的最小深度
//给定一个二叉树,找出其最小深度。
public static int minDepth(TreeNode root) {
//如何根节点为空,直接返回0
if (root == null) {
return 0;
}else if (root.left == null){//出现只有右子树的情况,那么递归遍历右子树
return minDepth(root.right) + 1;
}else if (root.right == null){//出现只有左子树的情况,那么递归遍历左子树
return minDepth(root.left) + 1;
}
//同时出现左右子树的情况
return Math.min(minDepth(root.left) + 1, minDepth(root.right) + 1);
}