题目一:二叉树的最小深度
解法:解决二叉树问题最好的方法永远是递归,其他的都是垃圾,这个解法未曾优化,怎么省事儿怎么来的 就是if else 判断一下 子节点是否为空 最后比较一下那边儿最小 不比较就崩了
public int minDepth(TreeNode root) {
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;
else return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
题目二:二叉树的最大深度
解法:比上题简单一点,这种题不能再简单了,不用判空子节点,直接比谁大就行了
public int maxDepth(TreeNode root) {
if (root == null)return 0;
else return Math.max(maxDepth(root.right),maxDepth(root.left))+1;
}