题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],返回它的最小深度 2
思路
重温一下:
二叉树的深度和高度:
对于二叉树某个节点的深度:从上往下数,从根节点到该节点的最长简单路径的节点个数,因此访问节点的深度要用先序遍历
对于二叉树某个节点的高度:从下往上数,从叶子结点到该节点的最长简单路径的节点个数,因此访问节点的高度要用后序遍历
每层节点的深度和高度如图所示:
前序求深度(前序—>从上往下—>深度)
后序求高度(后序—>从下往上—>高度)
审题:最小深度是从根节点到最近叶子节点的最短路径上的节点数量,一定要是叶子结点
- 递归法:
如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。
反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。
最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。
(因为一定要找到左子树右子树都为空的叶子节点)
class Solution {
public int minDepth(TreeNode root){
if(root == null){
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if(root.left == null){
return rightDepth + 1;
}
if(root.right == null){
return leftDepth + 1;
}
//如果左右节点都不为null,则取最小值,因为是求最小深度,即最近的叶子节点
return Math.min(leftDepth,rightDepth) + 1;
}
}
- 迭代法:用队列模拟广度遍历(层序遍历),用栈模拟深度遍历(前中后序遍历)
class Solution {
public int minDepth(TreeNode root){
if(root ==null){
return 0;
}
Deque<TreeNode> deque = new LinkedList<>();
deque.offer(root);
int depth = 0;
while(!deque.isEmpty()){
int size = deque.size();
depth++;
for(int i=0; i < size; i++){
TreeNode node = deque.poll();
if(node.left == null && node.right == null){
return depth;
}
if(node.left != null){//若左右子树非空则继续加入队列
deque.offer(node.left);
}
if(node.right != null){
deque.offer(node.right);
}
}
}
return depth;
}
}