My c++ solution in 15ms


  • 0
    W
    class Solution {
    public:
    int minDepth(TreeNode *root) {
        if(root==NULL)  return 0;
        if(root->left)  
           { if(root->right) return min(mm(root->left),mm(root->right))+1;
            else return mm(root->left)+1;}
        if(root->right) return mm(root->right)+1;
        return 1;
    }
    
    int mm(TreeNode *root){
        if(root->left)  
           { if(root->right) return min(mm(root->left)+1,mm(root->right)+1);
            else return mm(root->left)+1;}
        if(root->right) return mm(root->right)+1;
        return 1;
    }
    

    };

    There are three rules to solve this question:
    1.whether the node has both left and right pointers?
    if it does, start next recursion;
    2.whether the node has neither left and right pointers?
    If it does, return 1;
    3.Otherwise, if the node doesn't have left pointer,we need to search the right pointer.

    My submission uses the main recursion in another function. Since we don't need to check whether the root node is NULL or not,we have do this in the last step.
    Besides,my submission optimize the judgement function ,we don't need to have another if(ss==true) after if(ss == true && bb==true),that is a waste of time

    Please forgive me for my poor English = =


Log in to reply
 

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