KOKO-代码随想录算法训练营Day 16 | 104|111 |222
文章目录
一、104,二叉树的最大深度 (优先掌握递归)
1.题目
2.代码
public static int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return getDeep(root,0);
}
private static int getDeep(TreeNode root,int depth) {
/**
* 取左子树和右子树的最大深度
*/
if(root==null){
return depth;
}
depth++;
int leftD=getDeep(root.left,depth);
int leftR=getDeep(root.right,depth);
return Math.max(leftD,leftR);
}
3.总结
取左右子树较大的值。深度为根节点到最远叶子节点的路径上的节点数
二、111.二叉树的最小深度 (优先掌握递归)
1.题目
2.代码
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
return getMin(root,0);
}
private int getMin(TreeNode root, int i) {
if(root==null){
return i;
}
i++;
//最小路径是根节点到最近叶子节点的最短路径上的节点数量,一定是到叶子节点。
if(root.left!=null&&root.right==null){
return getMin(root.left,i);
}
if(root.left==null&&root.right!=null){
return getMin(root.right,i);
}
return Math.min(getMin(root.left,i),getMin(root.right,i));
}
3.总结
注意最小深度是从根节点出发到叶子节点,若根节点只有一个子树,则最小深度并不是1 .因此要判断左右节点同时不为null时再进行计算,一个为null,需要传入另一个子树。
三. 222.完全二叉树的节点个数(优先掌握递归)
1.题目:
2.代码:
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
int left=countNodes(root.left); //左子树
int right=countNodes(root.right); //右子树
return 1+left+right;
}
3.总结:
总结
左+右+1即可。,对左右子树进行计算。也可以用层序遍历,用result在弹出元素时做++即可。
while (!queue.isEmpty()) {
int size = queue.size();
while (size – > 0) {
TreeNode cur = queue.poll();
result++;
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
}