代码随想录训练营第16天|104.二叉树的最大深度,559.n叉树的最大深度,111.二叉树的最小深度,222.完全二叉树的节点个数
)
104.二叉树的最大深度
文章
思路
昨天用层序遍历做过一遍
今天用递归
空节点深度为0,非空节点深度等于左右节点深度最大值加1,根节点深度即为二叉树最大深度
代码
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
559.N叉树的最大深度
文章
思路
与二叉树最大深度类似
可以层序遍历
递归有一点点区别
空节点深度确实为0
但非空节点有空节点孩子的情况是不存在的,如果按二叉树相同方法递归,会因为叶子节点children为空列表而出bug,所以另一个递归的起点应该是叶子节点深度为1
代码
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
int ans = 1;
for (Node node: root.children) {
ans = Math.max(ans, maxDepth(node) + 1);
}
return ans;
}
}
111.二叉树的最小深度
文章
思路
一开始以为按照最大深度的递归做就行,但是不AC
bug出在一侧孩子节点为空但另一侧不为空的情况,所以我用if-else判断了
代码
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left != null && root.right != null)
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
else if (root.left == null)
return minDepth(root.right) + 1;
else
return minDepth(root.left) +1;
}
}
222.完全二叉树的节点个数
文章
思路
脱离完全二叉树的性质来做,可以递归或迭代
递归就是左子树节点数+右子树节点数+1
迭代就是遍历并计数
代码
class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
总结
没太领会完全二叉树的特殊性,再看看