4 ms C solution


  • 0
    C
    void findMin(struct TreeNode* node, int* minSoFar, int prev)
    {
        if (node == NULL)
        {
            return;
        }
        
        if (node->left == NULL && node->right == NULL)
        {
            if (prev+1 < *minSoFar)
            {
                *minSoFar = prev+1;
            }
        }
        
        findMin(node->left, minSoFar, prev+1);
        findMin(node->right, minSoFar, prev+1);
    }
    
    int minDepth(struct TreeNode* root) {
        
        int minSoFar = INT_MAX;
        
        if (root == NULL)
            return 0;
        
        findMin(root, &minSoFar, 0);
        
        return minSoFar;
    }

  • 0
    S

    mine is as similar as yours, but i think bfs is better than dfs.


  • 0
    G

    Agree. The code above actually browsed the whole tree.

    I thought the test case would include a situation where dfs will use too much time or memory. But obviously it does not include such case.


  • 0
    Y

    change if (node == NULL)
    to
    if (node == NULL || prev+1 >= *minSoFar)


Log in to reply
 

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