SoFunction
Updated on 2025-03-02

C++ implements LeetCode (111. Minimum depth of binary tree)

[LeetCode] 111. 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.

Example:

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

    3
/ \
9  20
/  \
15   7

return its minimum depth = 2.

The smallest depth problem of the classic binary tree is the number of nodes in the shortest path, or the depth-first search DFS is used to complete it. It is a universal recursion. First, judge empty. If the current node does not exist, return 0 directly. Then see if the left child node does not exist, then call the recursive function on the right child node and add 1 to return. On the contrary, if the right child node does not exist, then call the recursive function on the left child node and add 1 to return. If both left and right sub-nodes exist, then call the recursive function on the left and right sub-nodes respectively, and add 1 to the smaller value of the two, see the code as follows:

Solution 1:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        if (!root->left) return 1 + minDepth(root->right);
        if (!root->right) return 1 + minDepth(root->left);
        return 1 + min(minDepth(root->left), minDepth(root->right));
    }
};

We can also do iteratively, traverse in layer sequence, and record the number of layers traversed. Once we traverse to the first leaf node, the current number of layers will be returned, which is the minimum depth of the binary tree. See the code as follows:

Solution 2:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        queue<TreeNode*> q{{root}};
        while (!()) {
            ++res;
            for (int i = (); i > 0; --i) {
                auto t = (); ();
                if (!t->left && !t->right) return res;
                if (t->left) (t->left);
                if (t->right) (t->right);
            }
        }
        return -1;
    }
};

Github synchronization address:

/grandyang/leetcode/issues/111

Similar topics:

Binary Tree Level Order Traversal

Maximum Depth of Binary Tree

References:

/problems/minimum-depth-of-binary-tree/

/problems/minimum-depth-of-binary-tree/discuss/36153/My-concise-c%2B%2B-solution

/problems/minimum-depth-of-binary-tree/discuss/36071/BFS-C%2B%2B-8ms-Beats-99.94-submissions

This is the end of this article about C++ implementing LeetCode (111. Minimum depth of binary tree). For more relevant content on C++ implementing the minimum depth of binary tree, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!