最大深度
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
判断平衡树
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
public int height(TreeNode root) {
if (root == null) {
return 0;
}
// 深度优先遍历的变形
int leftHeight = height(root.left);
int rightHeight = height(root.right);
// 这里需要判断的条件还是否为 -1 因为如果是进入过这里的方法体里面那么就需要注意了判断 leftHeight == -1 如果是的那么一路返回 -1 就可以了
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight -rightHeight) > 1) {
return -1;
} else {
// 这里需要加 1 的,具体原因画一个示意图就可以知道了
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
二叉树最小深度
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
// 这个写在前面,也就意味着多进去一次,但是也没差,如果是根节点或者是对应的 左孩子或者右孩子是 null 那么返回的是还是 0
int leftDepth = minDepth(root.left); // 左
int rightDepth = minDepth(root.right); // 右
if (root.left == null) {
return rightDepth + 1;
}
if (root.right == null) {
return leftDepth + 1;
}
// 左右结点都不为null
return Math.min(leftDepth, rightDepth) + 1;
}
}
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int min_depth = Integer.MAX_VALUE;
if (root.left != null) {
min_depth = Math.min(minDepth(root.left), min_depth);
}
if (root.right != null) {
min_depth = Math.min(minDepth(root.right), min_depth);
}
return min_depth + 1;
}
}
这两个的区别就是终止条件
的不同
- 第一个写法 只有一个 node == null 返回 0 的这么一个条件,那么遍历的时候也会遍历根节点的下一个节点, 而且就算遍历根节点的下一个节点 null,进入之后返回 0 但是还有 两个 if 体条件是 null 也可以进去,所以不会出现少算的情况
- 第二种写法,两个终止条件其中包含了: 根节点直接返回 1 的终止条件,而且 if 条件是不能等于 null,如果没有这个终止条件同时根节点的下一个节点 null 也进不去,那么就会出现少算的情况