二叉树3| 104.二叉树的最大深度|111.二叉树的最小深度|222.完全二叉树的节点个数
一、104.二叉树的最大深度
题目连接:104. 二叉树的最大深度 - 力扣(LeetCode)
- 此题可采用前序遍历、后序遍历、层序遍历解决,后序遍历方法如下:
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int lh = maxDepth(root.left);//左
int rh = maxDepth(root.right);//右
return Math.max(lh, rh) + 1;//中
}
}
二、111.二叉树的最小深度
题目连接:111. 二叉树的最小深度 - 力扣(LeetCode)
- 注意:最小深度是从根节点到最近叶子节点的最短路径上的节点数量,叶子节点是指没有子节点的节点。取最小值的同时,注意会有左子树为空,右子树不为空的情况下应该取右子树的高度。
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int lh = minDepth(root.left);
int rh = minDepth(root.right);
if(root.left == null && root.right != null){
return rh + 1;
}
if(root.left != null && root.right == null){
return lh + 1;
}
return Math.min(lh, rh) + 1;
}
}
三、222.完全二叉树的节点个数
题目连接:222. 完全二叉树的节点个数 - 力扣(LeetCode)
- 将其当成普通二叉树遍历节点,后序遍历
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int left = countNodes(root.left);
int right = countNodes(root.right);
return left + right + 1;
}
}
- 利用完全二叉树的性质解题,后序遍历。先判断子二叉树是否是满二叉树,若是则利用2^n - 1计算节点个数;若不是则继续向下遍历,判断其子树是否是,返回节点个数。
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int lefedepth = 0;
int rightdepth = 0;
while(left != null){
left = left.left;
lefedepth++;
}
while (right != null){
right = right.right;
rightdepth++;
}
if(lefedepth == rightdepth) return (2<<lefedepth) - 1;
int leftnum = countNodes(root.left);
int rightnum = countNodes(root.right);
return leftnum + rightnum + 1;
}
}