摘要
本文主要介绍了LeetCode二叉树的几个题目,包括1104.二叉树的最大深度、111.二叉树的最小深度、222.完全二叉树的节点个数。
1、104.二叉树的最大深度
1.1 思路
- 递归遍历
- 二叉树的最大深度等于左子树或右子树的最大深度取最大值+1
1.2 代码
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
2、111.二叉树的最小深度
2.1 思路
- 递归遍历
- 二叉树的最小深度等于左右子树最小深度+1
- 如果二叉树的左子树或右子树为空,该二叉树的最小深度等于左子树或右子树的深度+1
2.2 代码
public int minDepth(TreeNode root) {
if(root == null) {
return 0;
}
if(root.left != null && root.right == null) {
return minDepth(root.left) + 1;
}
if(root.right != null && root.left == null) {
return minDepth(root.right) + 1;
}
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
3、222.完全二叉树的节点个数
3.1 递归
- 递归遍历,二叉树的节点个数等于左右节点个数之和+1
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
3.2 层序遍历
- 层序遍历:定义一个count做计数
public int countNodes(TreeNode root) {
int count = 0;
if(root == null) {
return count;
}
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while(!queue.isEmpty()) {
int size = queue.size();
for(int i=0; i<size; i++) {
TreeNode node = queue.pop();
count++;
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
}
return count;
}
3.3 完全二叉树
- 针对完全二叉树的解法
- 因为满二叉树的节点个数等于2^dept-1,如果该二叉树是满二叉树则可以直接计算出节点的个数
- 如何判断是满二叉树,因为题目中是完全二叉树,如果左子树的深度,等于右子树的深度,则认为是满二叉树
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
// 判断是否是满二叉树
int leftDepth = 0;
int rightDepth = 0;
TreeNode left = root.left;
TreeNode right = root.right;
while(left != null) {
left = left.left;
leftDepth++;
}
while(right != null) {
right = right.right;
rightDepth++;
}
if(leftDepth == rightDepth) {
// 注意(2<<1) 相当于2^2,所以leftDepth初始为0
return (2 << leftDepth) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}