二叉树模块
104.二叉树的最大深度
- 递归法: 当遍历到null时, 记录深度为0, 然后向上返回左右子树的最大深度 + 1
- 迭代法: 层序遍历, 层数即最大深度
代码:
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
111.二叉树的最小深度
- 递归法---需要判断当前节点是否为叶子节点和左右子节点为空的情况
- 迭代法---找到第一个叶子节点即可
代码:
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null){
return 1;
}else if(root.left == null){
return minDepth(root.right) + 1;
}else if(root.right == null) {
return minDepth(root.left) + 1;
}else {
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
}
222.完全二叉树的节点个数
- 递归法:递归到null, 返回0, 否则向上返回左子结点个数+右子结点个数+1
- 迭代法:统计栈里面经过多少个元素即可
代码:
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}