104.二叉树的最大深度
代码随想录
本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
而根节点的高度就是二叉树的最大深度,所以本题中我们通过后序求的根节点高度来求的二叉树最大深度。
递归遍历
- 确定递归参数
- 确定跳出条件
- 确定递归逻辑
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
111.二叉树的最小深度
注意这里有一个小坑:最小深度是从根节点到最近叶子节点的最短路径上的节点数量。注意是叶子节点。
什么是叶子节点,左右孩子都为空的节点才是叶子节点!
递归法和迭代法
public class LC111_minDepth {
// 递归法
public int minDepth(TreeNode root) {
if (root == null) return 0;
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if (root.left == null && root.right != null) {
return 1 + rightDepth;
}
if (root.left != null && root.right == null) {
return 1 + leftDepth;
}
return 1 + Math.min(leftDepth, rightDepth);
}
// 迭代法,层序遍历
public int minDepth2(TreeNode root) {
if (root == null) return 0;
Deque<TreeNode> que = new LinkedList<>();
int depth = 1;
que.offer(root);
while (!que.isEmpty()) {
int len = que.size();
while (len-- > 0) {
TreeNode node = que.poll();
if (node.left == null && node.right == null) {
return depth;
} else {
if (node.left != null) que.offer(node.left);
if (node.right != null) que.offer(node.right);
}
}
depth++;
}
return depth;
}
}
222.完全二叉树的节点个数
普通二叉树的节点个数计算比较好理解,跟求深度方法类似,只需要改一下。
直接递归或者层序遍历即可。
public int countNodes(TreeNode root) {
if (root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
利用完全二叉树特点计算:
完全二叉树只有两种情况:
- 情况一:就是满二叉树
- 情况二:最后一层叶子节点没有满
对于情况一,可以直接用 2^树深度 - 1 来计算,注意这里根节点深度为1。
对于情况二,分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后依然可以按照情况1来计算。
可以看出如果整个树不是满二叉树,就递归其左右孩子,直到遇到满二叉树为止,用公式计算这个子树(满二叉树)的节点数量。
如何判断一棵子树是不是满二叉树呢?
在完全二叉树中,如果递归向左遍历的深度等于递归向右遍历的深度,那说明就是满二叉树。如图:
左深度 = 右深度时,即为满二叉树。
public class LC222_countNodes {
public int countNodes(TreeNode root) {
if (root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
/**
* 针对完全二叉树的解法
*
* 满二叉树的结点数为:2^depth - 1
*/
public int countNodes2(TreeNode root) {
if (root == null) return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 0, rightDepth = 0;
while (left != null) {
left = left.left;
leftDepth++;
}
while (right != null) {
right = right.right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0
}
return countNodes2(root.left) + countNodes2(root.right) + 1;
}
}