今日内容:104.二叉树的最大深度、111.二叉树的最小深度、222.完全二叉树的节点个数 代码随想录链接:day16 (二叉树) (yuque.com)
104.二叉树的最大深度
给定一个二叉树
root,返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
这道题写过层序遍历的,这里用递归法写一下。
而根节点的高度就是二叉树的最大深度,所以本题中我们通过后序求的根节点高度来求的二叉树最大深度。
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
前序遍历的情况下,就需要创建一个全局变量result来记录深度。
class Solution {
public int result = 0;
public int maxDepth(TreeNode root) {
if(root == null)return result;
getdepth(root,0);
return result;
}
private void getdepth(TreeNode node, int depth){
if(node == null)return;
depth++;
result = result > depth ? result : depth;
getdepth(node.left,depth);
getdepth(node.right,depth);
depth--;
}
}
111.二叉树的最小深度
给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明: 叶子节点是指没有子节点的节点。
这道题也是层序做过
只有当左右孩子都为空的时候,才说明遍历到最低点了
这里用前面最大深度的写法(可理解为后序,但其实不是)来写。
class Solution {
int result = Integer.MAX_VALUE;
int depth = 0;
public int minDepth(TreeNode root) {
if (root == null) return 0;
getdepth(root);
return result;
}
private void getdepth(TreeNode node){
if(node == null)return;
depth++;
getdepth(node.left);
getdepth(node.right);
if(node.left == null && node.right == null){
result = result < depth ? result : depth;
}
depth--;
return;
}
}
前序写法(其实不能算前序)
class Solution {
int result = Integer.MAX_VALUE;
int depth = 0;
public int minDepth(TreeNode root) {
if (root == null) return 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;
}
return leftDepth < rightDepth ? leftDepth + 1 : rightDepth + 1;
}
}
222.完全二叉树的节点个数
给你一棵 完全二叉树 的根节点
root,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第h层,则该层包含1~ 2h个节点。
这题用层序遍历是可以写的
class Solution {
public int countNodes(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
int num = 0;
if(root == null)return 0;
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 0; i < len; i++){
TreeNode cur = queue.poll();
if(cur.left != null)queue.offer(cur.left);
if(cur.right != null)queue.offer(cur.right);
}
num = num + len;
}
return num;
}
}
用递归写法
单层递归的逻辑:先求它的左子树的节点数量,再求右子树的节点数量,最后取总和再加一 (加1是因为算上当前中间节点)就是目前节点为根节点的节点数量。
class Solution {
int num = 0;
public int countNodes(TreeNode root) {
if(root == null)return 0;
int leftnum = countNodes(root.left);
int rightnum = countNodes(root.right);
int sum = leftnum + rightnum + 1;
return sum;
}
}
完全二叉树 如果最左孩子和最右孩子的深度相同,则是完全二叉树,
class Solution {
int num = 0;
public int countNodes(TreeNode root) {
if(root == null)return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 0;
int rightDepth = 0;
while(left != null){
left = left.left;
leftDepth++;
}
while(right != null){
right = right.right;
rightDepth++;
}
if(leftDepth == rightDepth){
return(2 << leftDepth) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
注意(2<<1) 相当于2^2,所以leftDepth初始为0
结束