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.
本来以为bfs速度会很快,结果实际运行不是这样。
/**
* 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){
return 0;
}
queue<TreeNode*> q;
q.push(root);
int result = 0;
while(!q.empty()){
int size = q.size();
result++;
for(int i = 0; i != size; ++i){
TreeNode* temp = q.front();
q.pop();
if(!temp->left && !temp->right){
return result;
}
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
}
}
};
递归版本的
int minDepth(TreeNode *root) {
if(!root) return 0;
if(!root->left) return 1 + minDepth(root->right);
if(!root->right) return 1 + minDepth(root->left);
return 1+min(minDepth(root->left),minDepth(root->right));
}