Sharing my 12ms C++ solution


  • 2
    T
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int minDepth(TreeNode* root) {
            if(root==NULL)
                return 0;
            else if(root->left==NULL && root->right==NULL)
                return 1;
            else if(root->left == NULL)
                return minDepth(root->right)+1;
            else if(root->right == NULL)
                return minDepth(root->left)+1;
            else
                return min(minDepth(root->left), minDepth(root->right))+1;
        }
    };

  • 0
    O

    Hi

    Could you please explain why when 'root->left == NULL' is true, we need to do 'return minDepth(root->right)+1;', i.e. when the left child is empty, we return the minimum depth of the right child?

    Thanks!


Log in to reply
 

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