---
# System prepended metadata

title: Question 111. Minimum Depth of Binary Tree
tags: [leetcode]

---

###### tags: `leetcode`
# Question 111. 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.
### Solution:
- BFS:
    - collect all root, return the depth of the first occurs of root->left==NULL && root->right == NULL
- DFS:
    - cmpare the depth of left and right subtree.
### AC code
code1, DFS
```cpp=
#include <limits.h>
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    //DFS
    int minDepth(TreeNode* root) {
        if(root==NULL)
            return 0;
        if(root->left==NULL && root->right==NULL)
            return 1;
        if(root->left==NULL)
            return minDepth(root->right)+1;
        if(root->right==NULL)
            return minDepth(root->left)+1;
        return min(minDepth(root->left), minDepth(root->right))+1;
    }
```
code2, BFS, return when the first root->left == NULL && root->right == NULL occurs.
```cpp=
#include <limits.h>
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    //BFS
    int minDepth(TreeNode* root) {
        if(!root)
            return 0;
        queue<TreeNode*> r;
        r.push(root);
        int cnt = 0;
        TreeNode* tmp;
        while(!r.empty()){
            cnt++;
            int n = r.size();
            for(int i = 0 ; i < n ; i++){
                tmp = r.front();
                r.pop();
                if(!tmp->left && !tmp->right)
                    return cnt;
                if(tmp->left)
                    r.push(tmp->left);
                if(tmp->right)
                    r.push(tmp->right);
            }
        }
        return cnt;
    }
    
};
```