題目: 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.
思路:
兩種方法:
第一,使用遞歸,相當於遍歷了整個二叉樹,遞歸返回深度淺的那棵子樹的深度。
第二,按層檢查有沒有葉子節點,有的話停止檢查,返回當前層數。至於實現這個按層檢查,可以用遞歸的方法。該法不用遍歷整個樹。
--來自於
牛客426550號
由於我本人只想到第一種辦法,看到牛客友人
牛客426550號給的思路覺得考慮的比較周全,所以就在此引用一下。謝謝!
遞歸要分清楚幾種情況:
1、當根節點為空時,返回0
2、當只有左子節點(無右子節點)時,返回 1
3、當只有右子節點(無左子節點)時,返回 1
4、當左右子節點都存在時,分別計算左子樹和右子樹的深度,min(左子樹最小深度,右子樹最小深度)+1
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public int run(TreeNode root) { if(root!=null){ int left = Integer.MAX_VALUE; int right = Integer.MAX_VALUE; if(root.left!=null){ left = run(root.left); } if(root.right!=null){ right = run(root.right); } if(left<right){ return left+1; } else if(left>right){ return right+1; } else if(left==right&&left!=Integer.MAX_VALUE){ return left+1; } else return 1; } return 0; } }
當然,還有一個較簡潔的遞歸方法,最核心的思想就是根節點到達最近的葉子節點的路徑長度:
1、當根為空時,輸出0
2、當左子樹為空時,輸出右子樹深度+1
3、當右子樹為空時,輸出左子樹深度+1
4、以上條件都不滿足時,輸出min(左子樹深度,右子樹深度)+1
public class Solution { public int run(TreeNode root) { if(root==null) return 0; if(root.left==null) return run(root.right)+1; if(root.right==null) return run(root.left)+1; return Math.min(run(root.left),run(root.right))+1; } }
