4ms C language Solution


  • 0
    N
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    static int curMinDepth;
    void countDepth(struct TreeNode *node, int curDep)
    {
        if(!node->left && !node->right  && curDep < curMinDepth)
        {
            curMinDepth = curDep;
            return;
        }
        
        if(curDep + 1 >= curMinDepth)
        {
            return;
        }
        
        if(node->left)
        {
            countDepth(node->left, curDep + 1);
        }
        
        if(node->right)
        {
            countDepth(node->right, curDep + 1);
        }
    }
    int minDepth(struct TreeNode* root) {
        if(!root) return 0;
        curMinDepth = INT_MAX;
        countDepth(root, 1);
        return curMinDepth;
        
    }

  • 1
    L

    int leftDeth = 0;
    int rightDeth = 0;

        if(root == NULL)
            return 0;
        leftDeth = minDepth(root->left);
        rightDeth = minDepth(root->right);
        
        if(root->left && root->right)
            return leftDeth<rightDeth?leftDeth+1:rightDeth+1;
        else
            return leftDeth>rightDeth?leftDet+1:rightDeth+1;

Log in to reply
 

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