最小深度

来源:互联网 发布:政府网络不能玩皮皮 编辑:程序博客网 时间:2024/05/24 15:41

这道题是树的题目,其实跟Maximum Depth of Binary Tree非常类似,只是这道题因为是判断最小深度,所以必须增加一个叶子的判断(因为如果一个节点如果只有左子树或者右子树,我们不能取它左右子树中小的作为深度,因为那样会是0,我们只有在叶子节点才能判断深度,而在求最大深度的时候,因为一定会取大的那个,所以不会有这个问题)。这道题同样是递归和非递归的解法,递归解法比较常规的思路,比Maximum Depth of Binary Tree多加一个左右子树的判断,代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public int minDepth(TreeNode root) {  
  2.     if(root == null)  
  3.         return 0;  
  4.     if(root.left == null)  
  5.         return minDepth(root.right)+1;  
  6.     if(root.right == null)  
  7.         return minDepth(root.left)+1;  
  8.     return Math.min(minDepth(root.left),minDepth(root.right))+1;  
  9. }  
非递归解法同样采用层序遍历(相当于图的BFS),只是在检测到第一个叶子的时候就可以返回了,代码如下: 
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public int minDepth(TreeNode root) {  
  2.     if(root == null)  
  3.         return 0;  
  4.     LinkedList queue = new LinkedList();  
  5.     int curNum = 0;  
  6.     int lastNum = 1;  
  7.     int level = 1;  
  8.     queue.offer(root);  
  9.     while(!queue.isEmpty())  
  10.     {  
  11.         TreeNode cur = queue.poll();  
  12.         if(cur.left==null && cur.right==null)  
  13.             return level;  
  14.         lastNum--;  
  15.         if(cur.left!=null)  
  16.         {  
  17.             queue.offer(cur.left);  
  18.             curNum++;  
  19.         }  
  20.         if(cur.right!=null)  
  21.         {  
  22.             queue.offer(cur.right);  
  23.             curNum++;  
  24.         }  
  25.         if(lastNum==0)  
  26.         {  
  27.             lastNum = curNum;  
  28.             curNum = 0;  
  29.             level++;  
  30.         }  
  31.     }  
  32.     return 0;  
  33. }  
0 0
原创粉丝点击