内容:
- 二叉树的最大深度(104) N叉树的最大深度(559)
- 二叉树的最小深度(111)
- 完全二叉树的节点个数(222)
1.二叉树的最大深度 N叉树的最大深度
难度:🔥🔥🔥
建议:什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式,优先掌握递归
1.1 思路分析
本题使用后序遍历(左右中)求根节点的高度,即二叉树的最大深度。
N叉树的最大深度思路与之相似。
1.2 代码实现
二叉树的最大深度
class Solution {
public int maxDepth(TreeNode root) {
//后序遍历求最大高度(递归法),迭代法也很简单
if(root == null) return 0;
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
int height = 1 + Math.max(leftHeight,rightHeight);
return height;//返回子树的高度给上一层
}
}
N叉树的最大深度
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
int depth = 0;
if(root.children != null) {
for (int i = 0; i < root.children.size(); i++) {
depth = Math.max(depth, maxDepth(root.children.get(i)));
}
}
return depth + 1;
}
}
1.3 注意事项
1.4 收获总结
2.二叉树的最小深度
难度:🔥🔥
建议:和最大深度 看似差不多,其实差距还挺大,有坑,优先掌握递归
2.1 思路分析
最小深度是从根节点到最近叶子节点的最短路径上的节点数量
2.2 代码实现
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = minDepth(root.left);
int rightHeight = minDepth(root.right);
if (root.left == null) {
return rightHeight + 1;
}
if (root.right == null) {
return leftHeight + 1;
}
int result = Math.min(leftHeight,rightHeight);
return result + 1;
}
}
2.3 注意事项
2.4 收获总结
3.完全二叉树的节点个数
难度:🔥🔥🔥
建议:需要了解,普通二叉树 怎么求,完全二叉树又怎么求。优先掌握递归
3.1 思路分析
我们递归寻找完全二叉树的满二叉树。
如图:
![222.完全二叉树的节点个数](https://img-blog.csdnimg.cn/20201124092543662.png)
3.2 代码实现
普通二叉树递归
class Solution {
public int countNodes(TreeNode root) {
//递归
if (root == null) {
return 0;
}
int leftNum = countNodes(root.left);
int rightNum = countNodes(root.right);
return leftNum + rightNum + 1;
}
}
完全二叉树的递归
class Solution {
public int countNodes(TreeNode root) {
//针对完全二叉树的递归
if (root == null) {
return 0;
}
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 0,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;
}
}