题目:
111:给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
114:最大深度,同理;
思路:
-
BFS:按层搜索,首次出现叶子节点的那一层层数就是最小深度,最后一层出现叶子节点的层数就是最大深度;
-
DFS:找到每个叶子节点的层数,可得到最小深度和最大深度;
-
分治:如果同时存在左子树和右子树则,最小深度等于左子树和右子树中最小深度的最小值 + 1,否则等于存在的分支的最小深度 + 1;最大深度则等于左子树和右子树最大深度的较大值 + 1;
代码实现:
1,BFS:
private void bfs(TreeNode node){
if(node == null) return;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(node);
int level = 0;
while(!queue.isEmpty()){
int size = queue.size(); //获取当前层的元素个数
++level;
for(int i =0 ;i < size;++i){ //取完当前层即结束循环,进入外层循环维护层数
TreeNode nodeTemp = queue.poll();
if(nodeTemp.left == null && nodeTemp.right == null){
min = min > level ? level : min; //如果仅仅是找最小深度,则第一次找到就可以返回了,这里是最大最小深度都找了,所以没有返回
max = max > level ? max : level;
}
if(nodeTemp.left != null)
queue.offer(nodeTemp.left);
if(nodeTemp.right != null)
queue.offer(nodeTemp.right);
}
}
}
2 DFS:
private void dfs(TreeNode node ,int level){
if(node.left == null && node.right == null){
min = min > level + 1 ? level + 1 : min;
max = max > level + 1 ? max : level + 1;
return;
}
//以下过滤条件在寻找最小深度时可以删除注释,能屏蔽一些不必要的分支,加快速度;最大深度不能有这个条件判断;
// if(level >= min - 1){
// return;
// }
if(node.left != null)dfs(node.left,level+1);
if(node.right != null)dfs(node.right,level+1);
}
- 分治:
最大深度:
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
}
}
最小深度:
class Solution {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left != null && root.right != null){
return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
}
if(root.left != null){
return minDepth(root.left)+1;
}
if(root.right != null){
return minDepth(root.right) + 1;
}
return 1;
}
}
//或者写为以下代码,但上面的代码逻辑更为清晰;
class Solution {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
public int minDepth(TreeNode root) {
if(root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
return left == 0 || right == 0 ? left + right + 1 : Math.min(left,right)
+ 1;
}
}