/** * 求二叉树的最大深度和最小深度 */
public class Test1 {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
System.out.println(maxDepth(root));
System.out.println(minDepth(root));
}
public static int maxDepth(TreeNode root) {
if (root == null) return 0;
int left = maxDepth(root.left); //左子树的最大深度
int right = maxDepth(root.right); //右子树的最大深度
return left > right ? left + 1: right + 1;
}
public static int minDepth(TreeNode root) {
if (root == null) return 0;
int left = minDepth(root.left); //左子树的最小深度
int right = minDepth(root.right); //右子树的最小深度
return left < right ? left + 1: right + 1;
}
}
还没有评论,来说两句吧...