Concise recursive solution in C++


  • 0
    S
    int minDepth(TreeNode *root) {
        if (!root)      return 0;
        if (!root->left || !root->right)    return 1+max(minDepth(root->left), minDepth(root->right));
        else                                return 1+min(minDepth(root->left), minDepth(root->right));
    }
    

    My idea is simple. If both children exist, shorter depth is computed. Otherwise, which means either only one child or no child exists, we need to take longer depth.


Log in to reply
 

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