题目
题解
DFS
主要是要注意到有树成一条链的情况(即所有节点都只有一个孩子),所以不能直接return Math.min(minDepth(root.left),minDepth(root.right))+1;
,需要讨论左右子是不是空
class Solution {
private int depth=0;
public int minDepth(TreeNode root) {
if(root==null)
return 0;
if(root.left==null)
return minDepth(root.right)+1;
if(root.right==null)
return minDepth(root.left)+1;
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( h ) O(h) O(h)
BFS
BFS遍历树,记录层数,遇到第一个叶子节点即返回当前层数
class Solution {
private int depth=0;
public int minDepth(TreeNode root) {
if(root==null)
return 0;
Queue<TreeNode>queue=new LinkedList<>();
queue.offer(root);
int level=1;
while(!queue.isEmpty()){
int levelSize=queue.size();//每层节点数目
for(int i=0;i<levelSize;i++){
TreeNode node=queue.poll();
if(node.left==null&&node.right==null)
return level;//遇到的第一个叶子节点,返回深度
if(node.left!=null)
queue.offer(node.left);
if(node.right!=null)
queue.offer(node.right);
}
level++;//层数+1
}
return level;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)