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.
Tree Depth-first SearchHave you met this question in a real interview?
思路:同样还是树的递归问题,dfs深度遍历一下就行,这类问题的解法比较固定。本题用到优先队列(默认从小到大),所以直接出队,就是最小深度值。
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
public int minDepth(TreeNode root) {
if(root==null) return 0;
dfs(root,0);
return queue.poll();
}
public void dfs(TreeNode root,int count){
if(root==null){
return;
}else{
count++;
if(root.left==null&&root.right==null){
queue.add(count);
return;
}
}
dfs(root.left,count);
dfs(root.right,count);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
//这里bfs没用队列,是因为要对每一层的节点进行判断,用队列体现不出每一层的处理
//除非向队列中存入键值对,键是树节点,值是这个节点所在的层数,感觉有点麻烦
ArrayList<TreeNode> last = new ArrayList<TreeNode>();
last.add(root);
int count = 1;
while(!last.isEmpty()){
ArrayList<TreeNode> cur = new ArrayList<TreeNode>();
for(TreeNode treeNode:last){
if(treeNode.left==null&&treeNode.right==null){
return count;
}else{
if(treeNode.left!=null){
cur.add(treeNode.left);
}
if(treeNode.right!=null){
cur.add(treeNode.right);
}
}
}
last = cur;
count++;
}
return count;
}
}
之前的求二叉树镜像的就可以用BFS,对每一层的每个节点交换其左右子节点。那里不需要对层处理,所以直接可以用队列queue。思想都是类似的
参考博客:http://blog.csdn.net/sbitswc/article/details/26526031