题目
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its minimum depth = 2.
我的尝试
递归解法
这个题目类似于求二叉树的最大深度,先用递归方法解决:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
int minLeft=minDepth(root.left);
int minRight=minDepth(root.right);
if(minRight==0||minLeft==0)
return minLeft+minRight+1;
return 1+Math.min(minLeft,minRight);
}
}
我最开始的写法,对于[1,2]这个情况不对,题目期待结果为2,我的是1,如果没有节点,找到最近的叶子节点,所以增加了if判断,如果left或者right为空的情况。
非递归解法
最大深度用的是BFS解法,这里也用BFS解法尝试一下。在发现left和right都为空的时候,这个深度应该就是最小深度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
Deque<TreeNode> queue=new LinkedList();
queue.add(root);
int count=0;
boolean isBreak=false;
while(!queue.isEmpty()&&!isBreak){
int size=queue.size();
while(size-->0){
TreeNode treeNode=queue.poll();
if(treeNode.left==null&&treeNode.right==null){
isBreak=true;
}
if(treeNode.left!=null){
queue.addLast(treeNode.left);
}
if(treeNode.right!=null){
queue.addLast(treeNode.right);
}
}
count++;
}
return count;
}
}