111-Minimum Depth of Binary Tree

kevin聰發表於2018-05-03

Description

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.

Note: A leaf is a node with no children.


Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.


問題描述

給定一個二叉樹, 返回它的最低高度

最低高度為根節點到最近的葉節點的路徑的節點數


問題分析

與求高度類似, 需要注意節點的左右子樹為空的情況


解法

public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null)   return 0;

        int left = minDepth(root.left);
        int right = minDepth(root.right);
        //注意這裡的兩項判斷, 必須是根節點到葉子節點
        if (left == 0)  return 1 + right;
        if (right == 0) return 1 + left;

        return 1 + Math.min(left, right);
    }
}

相關文章