原题目:111. Minimum Depth of Binary Tree
代码:
BFS+逐层遍历,如果队列头结点的左右孩子都是null,返回深度。
代码:
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
queue<TreeNode*> q;
q.push(root);
TreeNode* tmp;
int ans=0,size;
while(!q.empty()){
ans++;
size = q.size();
for(int i=0;i<size;i++){
tmp = q.front();q.pop();
if(tmp->left==NULL && tmp->right==NULL) return ans;
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
return 0;
}
};