题目描述
minimum-depth-of-binary-tree
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.
问题分析:这个题有两种办法:第一种就是直接递归调用,这个办法好处就是理解起来方便,但是却需要把所有的节点都遍历一下,然后求出来最短的那个,需要的时间为T(n)。第二种就是采用层次遍历,这样哪怕树的结构是满二叉树,遍历到第一个节点的时候也可以结束,假如树高度为h,那我们遍历到2^(h-1) 的时候就可以结束遍历了,后面还有2^(h-1)-1个节点不用遍历。如果不是满二叉树,那需要遍历的就更少了,平均下来递归调用需要遍历T(n)次,层次遍历需要T(n/4)次,这里n代表节点总数。
代码如下:
递归算法:
public class Solution {
public int run(TreeNode root) {
if(root==null)
return 0;
if(root.left==null&&root.right==null)
return 1;
if(root.left==null || root.right==null)
return Math.max(run(root.left),run(root.right))+1;
return Math.min(run(root.left),run(root.right))+1;
}
}
非递归的层次遍历算法:(推荐)
import java.util.*;
public class Solution {
public int run(TreeNode root) {
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
Queue queue = new LinkedList();
queue.add(root);
int level = 1;
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 level;
}
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
level++;
}
return level;
}
}