风言枫语  

 

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

 

int minDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root == NULL) return 0;
        queue<TreeNode*> que;
        que.push(root);
        int count = 1;
        int depth = 0;
        while(!que.empty())
        {
            TreeNode* tmp = que.front();
            que.pop();
            count--;
            
            if(tmp->left == NULL && tmp->right == NULL) break;
            
            if(tmp->left)
                que.push(tmp->left);
            if(tmp->right)
                que.push(tmp->right);
            
            if(count == 0){
                depth++;
                count = que.size();
            }
        }
        return ++depth;
    }


 

 

posted on 2013-09-21 11:51  风言枫语  阅读(96)  评论(0编辑  收藏  举报