코딩테스트/BFS,DFS

[leetCode] 111. Minimum Depth of Binary Tree

minkg3532 2026. 5. 28. 22:29

https://leetcode.com/problems/minimum-depth-of-binary-tree/description/

 

Minimum Depth of Binary Tree - LeetCode

Can you solve this real interview question? 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 no

leetcode.com

 

이번엔 가장 얕은 깊이를 구하는 것이다. 104번 leetCode문제와 정반대 방향을 지향하고 있다.

더보기
더보기
/**
 * 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:
    int minDepth(TreeNode* root) 
    {
        queue<TreeNode*> q;
        q.push(root);
        int depth = 1;

        while(!q.empty())
        {
            int levelSize = q.size();

            for(int i=0; i<levelSize; i++)
            {         
                TreeNode* node = q.front();
                if(node == nullptr)
                    return 0;
                q.pop();

                if(node->left ==nullptr&& node->right == nullptr)   
                    return depth;
                
                if(node->left)
                    q.push(node->left);
                if(node->right)
                    q.push(node->right);
            }
            depth++;
        }

        return depth;
    }
};

 

아래는 DFS로 푼 방법이다.

더보기
더보기
/**
 * 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 {
private:
    int countDepth;
public:
    int minDepth(TreeNode* root) 
    {
       countDepth = INT_MAX;
       Search(root, 0);
       return countDepth;
    }

    void Search(TreeNode* node, int depth)
    {
        if(node == nullptr)
        {
            if(depth == 0)
                countDepth = 0;
            depth -=1;
            return;
        }

        Search(node->left, depth+1);
        Search(node->right, depth+1);
        if(node->left == nullptr && node->right == nullptr &&countDepth>depth)
        {
            countDepth = depth + 1;
        }
    }
};