1 题目链接
2 题目要求
描述
求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
示例
输入:{1,2,3,4,5}
返回值:2
3 代码思路
法一:使用递归完成。分为三种情况:空树、左子树或右子树为空、左右子树都不为空。
如果当前树是空树,则返回高度0即可。
如果左子树或右子树为空。左子树为空时,如我们要计算{F,#,I}的最小高度,我们只需要计算右子树{I}的最小高度加上当前节点{F}的高度即可。右子树为空时,如我们要计算{C,F,#,#,I}的最小高度,只需要计算{F,#,I}的最小高度加上{C}的高度即可。
如果左右子树都不为空。如我们要计算{C,F,G,#,I}的最小高度,我们需要比较左子树和右子树高度,取较小的一个返回。
法二:使用队列层次遍历计算高度。
对二叉树进行层次遍历,并记录每一层的高度。在遍历过程中,第一次遇到左右子树都为空的节点,返回所在高度,即为最小高度。如下图,层次遍历过程中,第一次遇到的左右子树都为空的节点为G,返回G所在的高度2,即为该二叉树的最小高度。
4 代码实现
法一:递归法。
public class Solution {
public int run (TreeNode root) {
// 空树时高度为0
if(root == null)
return 0;
// 左子树或右子树为空时
if(root.left == null)
return run(root.right) + 1;
if(root.right == null)
return run(root.left) + 1;
// 左右子树都不为空时
return Math.min(run(root.left),run(root.right)) + 1;
}
}
法二:队列层次遍历法。
public class Solution {
public int run (TreeNode root) {
if(root == null)
return 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int level = 1; // 记录当前遍历的层次
// 遍历二叉树
while(!queue.isEmpty()){
int size = queue.size();
// 遍历某一层
for(int i = 0; i < size; i++){
TreeNode temp = queue.poll();
// 第一次遇到某节点左右子树都为空时,返回高度
if(temp.left == null && temp.right == null){
return level;
}
if(temp.left != null) queue.offer(temp.left);
if(temp.right != null) queue.offer(temp.right);
}
level++;
}
return -1;
}
}
5 知识补充
参考博客: