1. 程式人生 > >leetcode 111-二叉樹最小深度

leetcode 111-二叉樹最小深度

最小深度定義為根節點到最近葉子節點的深度

分析:
空樹,最小深度為0
左右子樹都為空,最小深度為1
左右子樹不都為空,左右子樹中有空樹的情況,最小深度一定是在非空樹中產生,因為最小深度定義為到最近葉子節點的深度。一旦左右子樹有空的情況,這邊的深度就可以置為正無窮,表示最小深度不可能再這裡產生。然後分別計算左右子樹的最小深度,使用遞迴策略。

程式碼:

public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right
== null) return 1; int left, right; if (root.left != null) left = minDepth(root.left); else left = Integer.MAX_VALUE; if (root.right != null) right = minDepth(root.right); else right = Integer.MAX_VALUE; return Math.min(left, right) + 1; }