今日任务
104. 二叉树的最大深度 559. N 叉树的最大深度
二叉树的最小深度
完全二叉树的节点个数
代码随想录
104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
这题上次写过迭代的解法,这次写下递归的解法。通过左子树->左子树,右子树->右子树每递归一层深度加一即可。
🍅 递归解法,即重复调用函数来完成深度的叠加(后序遍历)
class Solution {
public int maxDepth(TreeNode root) {
if (root==null) return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return 1+Math.max(leftDepth,rightDepth);
}
}
559. N 叉树的最大深度
给定一个n叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
🍅 递归解法,即重复调用函数来完成深度的叠加
class Solution {
public int maxDepth(Node root) {
int deep = 0;
if (root == null) return 0;
else{
for(Node child : root.children) {
if (child !=null){
deep = Math.max(deep,maxDepth(child));
}
}
}
return deep+1;
}
}
🍅 迭代解法,即层序遍历二叉树得到最大深度
在每层队列(每一层结点)遍历完后,深度deep+1,最后返回deep即可
class Solution {
public int maxDepth(Node root) {
Queue<Node> que = new LinkedList<>();
int deep = 0;
if (root==null) return 0;
que.add(root); //把二叉树入队
while(!que.isEmpty()){
int len = que.size(); //定义len用来控制每层循环
while(len>0){
Node node = que.poll(); //提取队里的元素
//入队操作
for (Node child : node.children) {
que.add(child);
}
len--;
}
deep++;
}
return deep;
}
}
111. 二叉树的最小深度
要注意的是当左结点为空,右结点不为空时,返回的的应是右结点的最小深度+1,右结点则相反。
class Solution {
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 1+rightDepth;
}
if (root.right == null) { //当右结点为空时
return 1+leftDepth;
}
return Math.min(leftDepth,rightDepth)+1;
}
}
222. 完全二叉树的节点个数
第一种解法是层序遍历,这个方法之前写过,这次写下基于满二叉树的递归解法
🍅 基于满二叉树的递归解法,后序遍历得到结点数量
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int leftNum = getNum(root.left);
int rightNum = getNum(root.right);
int res = leftNum + rightNum + 1;
return res;
}
//当左右子树的深度一样时,那么可以快速得出结点数量为2*层数-1,
//如果不一样则结点数量+1,进入下一层继续判断进行递归
int getNum(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 getNum(root.left)+ 1 + getNum(root.right);
}
}
🍅 递归解法(适用所有二叉树)解法,后序遍历二叉树得到结点数量
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int leftnum = countNodes(root.left);
int rightnum = countNodes(root.right);
int result = leftnum + rightnum+1;
return result;
}
}