1. 程式人生 > >Minimum Depth of Binary Tree -- LeetCode

Minimum Depth of Binary Tree -- LeetCode

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

                原題連結: http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/  

這道題是樹的題目,其實跟Maximum Depth of Binary Tree

非常類似,只是這道題因為是判斷最小深度,所以必須增加一個葉子的判斷(因為如果一個節點如果只有左子樹或者右子樹,我們不能取它左右子樹中小的作為深度,因為那樣會是0,我們只有在葉子節點才能判斷深度,而在求最大深度的時候,因為一定會取大的那個,所以不會有這個問題)。這道題同樣是遞迴和非遞迴的解法,遞迴解法比較常規的思路,比Maximum Depth of Binary Tree多加一個左右子樹的判斷,程式碼如下:

public int minDepth(TreeNode root) {    if(root == null)        return
0;    if(root.left == null)        return minDepth(root.right)+1;    if(root.right == null)        return minDepth(root.left)+1;    return Math.min(minDepth(root.left),minDepth(root.right))+1
;}
非遞迴解法同樣採用層序遍歷(相當於圖的BFS),只是在檢測到第一個葉子的時候就可以返回了,程式碼如下: 
public int minDepth(TreeNode root) {    if(root == null)        return 0;    LinkedList queue = new LinkedList();    int curNum = 0;    int lastNum = 1;    int level = 1;    queue.offer(root);    while(!queue.isEmpty())    {        TreeNode cur = queue.poll();        if(cur.left==null && cur.right==null)            return level;        lastNum--;        if(cur.left!=null)        {            queue.offer(cur.left);            curNum++;        }        if(cur.right!=null)        {            queue.offer(cur.right);            curNum++;        }        if(lastNum==0)        {            lastNum = curNum;            curNum = 0;            level++;        }    }    return 0;}


           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述