# 111. Minimum Depth of Binary Tree

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/minimum-depth-of-binary-tree/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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******


思路，看完题目我想当然的认为就是直接递归取最小的值，代码如下：
```
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        return 1 + min(map(self.minDepth, (root.left, root.right)))
```


但是没过，有一种特殊情况就是

注意```leaf node```: 反正就是没有```left```和```right```的

比如下图


```
1
 \
  2
```

```2```是一个孩子节点

这种情况应该输出```2```而不是```1```



唯一的特殊情况就是上面这种了，因为```root```下只有一个左节点或者是右节点，这样另外一边的空节点并不算是```leaf node```

```leaf node: itself is not null but it has both children null```

所以还是要养成多写edge case的好习惯，也许就帮你避免了general写法的特例,代码如下

```python
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        elif root.left and root.right:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
        elif root.left:
            return 1 + self.minDepth(root.left)
        elif root.right:
            return 1 + self.minDepth(root.right)
        else:
            return 1
```




> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

或许写的更巧妙一些

```python
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        depth_under_root = map(self.minDepth, (root.left, root.right))
        return 1 + (min(depth_under_root) or max(depth_under_root))
```
