My 18ms c++ solution


  • 0
    S
    class Solution {
    public:
        int minDepth(TreeNode *root) {
            if(root==NULL) return 0;
            int count=1;
            queue<TreeNode *>q;
            q.push(root);
            TreeNode divide(0);
            q.push(&divide);
            while(!q.empty()){
                TreeNode *temp=q.front();
                q.pop();
                if(temp==&divide){
                    if(q.empty()) break;
                    count++;
                    q.push(&divide);
                }
                else{
                    if(temp->left) q.push(temp->left);
                    if(temp->right) q.push(temp->right);
                    if(temp->left==NULL&&temp->right==NULL) return count;
                }
            }
            return count;
       
        }
    };
    

    A mistake could take place if we don't know clearly what a leaf node means.
    A leaf node cannot have children, so we should exclude those nodes who have either left or right.


Log in to reply
 

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