104.二叉树的最大深度
-
题目链接:代码随想录
-
解题思路:
1.本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。
而根节点的高度就是二叉树的最大深度2.本题采用后序遍历求高度,前序遍历求高度设计回溯,二刷再看
使用递归思路解决(后序遍历)
①确定返回值和传入参数:返回值必定为int类型,因为要统计高度;一定要有参数,计算每一个根节点的最大高度
②处理逻辑:
每传入一个节点,节点不为空,那么deep++;
③终止条件:
传入root为空
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftLength = maxDepth(root.left);
int rightLength = maxDepth(root.right);
int depth = Math.max(leftLength, rightLength) + 1;//这里加一考虑根节点
return depth;
}
- 解决N叉树的高度问题:
- 解题思路:和解决二叉树高度的思路一样
public int maxDepth(Node root) {
if(root == null){
return 0;
}
//这里声明,用于Max比较
int depth = 0;
if(root.children != null){
for(Node child : root.children){
depth = Math.max(depth,maxDepth(child));//这里不能+1,因为如果这里+1的话,那么如果有三个节点,就加了三个1,多加了1个
}
}
return depth + 1;//这里返回每一层的最大高度 + 1
}
111.二叉树的最小深度
题目链接:代码随想录
- 解题思路:
此题与求解二叉树的最大高度思路大致一致,区别在于判断叶子节点上
再求一个树的最小高度上,只有遍历到叶子结点才是求最小高度,如果遍历的节点不是叶子结点,那么就不能在这个结点出得出最小高度
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 rightDepth + 1;//这种情况属于是左边结点,右边有的情况
}
if(root.right == null && root.left != null){
return leftDepth + 1;
}
//两边都有节点或者都没有结点
int depth = Math.min(leftDepth, rightDepth) + 1;
return depth;
}
222.完全二叉树的节点个数
题目链接:代码随想录
-
解题思路
①完全二叉树只有两种情况,情况一:就是满二叉树,情况二:最后一层叶子节点没有满。
对于情况一,可以直接用 2^树深度 - 1 来计算,注意这里根节点深度为1。
对于情况二,分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后依然可以按照情况1来计算。
②递归思路:
如果整个树不是满二叉树,就递归其左右孩子,直到遇到满二叉树为止,用公式计算这个子树(满二叉树)的节点数量(统计数据依据)。
③如何判别是不是满二叉树:递归向左遍历的深度等于递归向右遍历的深度
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
TreeNode left = root.left;
TreeNode right = root.right;
int leftDeep = 0;
int rightDeep = 0;
while(left != null){
left = left.left;
leftDeep++;
}
while(right != null){
right = right.right;
rightDeep++;
}
//这里确定是一棵满二叉树
if(leftDeep == rightDeep){
return (2 << leftDeep) - 1;// 2 << 1 相当于2的2次方,所以这里leftDeep
}
//这里确定不是满二叉树
return countNodes(left) + countNodes(right) + 1;
}
-
统计一个二叉树节点的通用思路:
先遍历左子树,统计节点;然后遍历右子树,统计节点;最后返回左右子树的节点个数再 + 根节点
public int countNodes(TreeNode root) { if(root == null){ return 0; } //左 int leftNum = countNodes(root.left); //右 int rightNum = countNodes(root.right); //中 int count = leftNum + rightNum + 1; return count; }