Minimum Depth of Binary Tree -- LeetCode
阿新 • • 發佈:2018-11-16
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
原題連結: http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/這道題是樹的題目,其實跟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;}