给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
1.自己的解法:思想类似于求最大深度,但是要判断叶子节点可能出现在哪些子树中。即深度优先遍历。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root == null){//如果当前节点为空,返回
return 0;
}
if(root.left == null && root.right != null){//左子树不存在,但是右子树存在,表明叶子节点只能出现在右子树中,因此计算右子树的最小深度即可
return minDepth(root.right) + 1;
}else if(root.left != null && root.right == null){//左子树存在,但是右子树不存在,表明叶子节点只能出现在左子树中,因此计算右子树的最小深度即可
return minDepth(root.left) + 1;
}else{
return Math.min(minDepth(root.left),minDepth(root.right)) + 1;//左右子树均存在的情况,计算两棵子树比较后的最小深度
}
}
}
2.答案解法:广度优先遍历。一层一层遍历。广度优先搜索的性质保证了最先搜索到的叶子节点的深度一定最小。
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {//树为空,返回0
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();//利用队列来存储遍历到的每一个节点
int minDepth = 1;//记录最小深度
queue.offer(root);
while(!queue.isEmpty()){//还有节点未被遍历
int size = queue.size();
for(int i = 0;i < size;i++){//一层一层地遍历节点
TreeNode node = queue.poll();
if(node.left == null && node.right == null){//如果在遍历当前层中某一个节点的左右子树均为空,即找到了第一个叶子节点,此时直接返回深度
return minDepth;
}
if(node.left != null){//左子节点不为空,加入队列
queue.offer(node.left);
}
if(node.right != null){//右子节点不为空,加入队列
queue.offer(node.right);
}
}
minDepth++;//遍历完一层后,深度加1
}
return minDepth;
}
}
题源:力扣