1. 程式人生 > >LeetCode-111.二叉樹的最小深度(相關話題:深度優先)

LeetCode-111.二叉樹的最小深度(相關話題:深度優先)

給定一個二叉樹,找出其最小深度。

最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。

說明: 葉子節點是指沒有子節點的節點。

示例:

給定二叉樹 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度 2.

Java程式碼:

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