今日主要题目
主要学习网址
做题思路与具体代码
题目一:104.二叉树的最大深度
做题思路
本题主要采用递归+后序遍历的解法,主要要注意求最大深度就是求最大高度
具体代码
class Solution {
public int maxDepth(TreeNode root) {
//采用递归+后序遍历的解法
//左右中的顺序
//一般用于左右值相加等于中间值
//求中间值
//逐渐往下走
//求深度,反向就是求高度
//特殊情况同时也是终止条件!!!
if(root==null){
return 0;
}
//左节点深度
int leftheight=maxDepth(root.left);
//右节点深度
int rightheight=maxDepth(root.right);
//结果等于两者其中最大值+1
int result=1+Math.max(leftheight,rightheight);
return result;
}
}
题目二:111.二叉树的最小深度
做题思路
本题同样采用递归+后序遍历的方法求深度,不一样的是用到的是Math.min,基本与上一题写法一致
具体代码
class Solution {
public int minDepth(TreeNode root) {
//前序求深度,后序求高度
//但是我们一般用后序求深度
//同样采用递归+后序遍历解法
//为空,返回0
if(root==null)return 0;
//左子树的最小深度
int left=minDepth(root.left);
//右子树的最小深度
int right=minDepth(root.right);
//因为题目是最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
//是到叶子节点
//所以要排除左边或右边为空的情况
if(root.left==null){
//返回右子树的最小深度
return 1+right;
}
if(root.right==null){
//返回左子树的最小深度
return 1+left;
}
//左右都不为空,返回左右子树最小深度的较小值
//说明还不是最小节点
return 1+Math.min(left,right);
}
}
题目三:222.完全二叉树的节点个数
做题思路
左右深度相同,证明是满二叉树,采用递归+后序遍历的方式,左右同时往右走测量深度,深度一样的话就是完全二叉树
具体代码
class Solution {
public int countNodes(TreeNode root) {
//使用递归+后序遍历的做法
//利用满二叉树的节点计算减少时间复杂度
//极端条件
if(root==null)return 0;
//初始化左右子树的值,方便遍历想加
int leftsum=0;
int rightsum=0;
//用来遍历
TreeNode left = root.left;
TreeNode right= root.right;
//遍历左边子树深度
while(left!=null){
left=left.left;
leftsum++;
}
//遍历右边子树深度
while(right!=null){
right=right.right;
rightsum++;
}
//如果左右深度相同,证明是满二叉树,返回2^depth - 1
if(leftsum==rightsum) return (2<<leftsum) - 1;
//后序相加
return countNodes(root.left) + countNodes(root.right) + 1;
}
}