# 111. Minimum Depth of Binary Tree

<https://leetcode.com/problems/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.

**Note:** A leaf is a node with no children.

注意是節點數！

cal sub tree node -> postorder

{% embed url="<https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/254240/Readable-code-from-the-definition-of-the-minimum-depth>" %}

因為有可能這樣一個很歪斜的樹, 所以如果用 dfs 要考慮這個狀況

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2FhMGqV7xcSmk6wUgWaI3E%2Fimage.png?alt=media\&token=df7c168c-8ca7-42e2-8bcb-d43e6061e9b4)

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

答案是 3, 9 -> 2 (2 node

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2FzdstKn6HLeJq3RXHV4l3%2Fimage.png?alt=media\&token=611c2a4c-f988-4234-bdb1-3de2355877fb)

### use BFS

````java
```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    class Step {
        TreeNode node;
        int level; 
        Step(TreeNode node, int level) {
            this.node = node;
            this.level = level;
        }
    }
    public int minDepth(TreeNode root) {
        Queue<Step> queue = new LinkedList<>();
        if (root == null) {
            return 0;
        }
        queue.offer(new Step(root, 0));

        int min = Integer.MAX_VALUE;
        while (!queue.isEmpty()) {
            Step cur = queue.poll();
            TreeNode node = cur.node;
            if (node == null) {
                continue;
            }
            if (node.left == null && node.right == null) {
                min = Math.min(min, cur.level+1);
            }
            queue.offer(new Step(node.left, cur.level+1));
            queue.offer(new Step(node.right, cur.level+1));
        }
        return min;
    }
}
```
````
