Another recursive solution, 9ms


  • 0
    S

    I've seen some concise 3-line recursive solutions in this forum. I try to implement that and that takes 13ms. Here I come up with another recursive approach which takes 9ms.

    class Solution {
    public:
        int minDepth(TreeNode* root) 
        {
            if (!root) return 0;
            int result = INT_MAX;
            bool end = true;
            find_min(root, 1, result, end);
            return result;
        }
        
        void find_min(TreeNode* root, int depth, int& result, bool end)
        {
            if (root->left) 
            {
                end = false; 
                find_min(root->left, depth + 1, result, true);
            }
            if (root->right) 
            {
                end = false;
                find_min(root->right, depth + 1, result, true);
            }
            //if end is true, it is a leaf node
            //we compare the local min depth to global min depth
            if (end) result = min(depth, result);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.