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.
class Solution {
public:
int minDepth(TreeNode* root) {
int ret=1000000;
if(!root) return 0;
help(root,1,ret);
return ret;
}
private:
void help(TreeNode* root,int depth,int& ret)
{
if(!root->left&&!root->right)
ret=min(depth,ret);
else if(root->left&&root->right)
{
help(root->left,depth+1,ret);
help(root->right,depth+1,ret);
}
else if(root->right&&!root->left)
help(root->right,depth+1,ret);
else
help(root->left,depth+1,ret);
}
int min(int a,int b)
{
return a<b?a:b;
}
};
呵呵哒,老子很失落!
学习下大佬的代码:BFS
int minDepth(TreeNode* root) {
if (root == NULL) return 0;
queue<TreeNode*> Q;
Q.push(root);
int i = 0;
while (!Q.empty()) {
i++;
int k = Q.size();
for (int j=0; j<k; j++) {
TreeNode* rt = Q.front();
if (rt->left) Q.push(rt->left);
if (rt->right) Q.push(rt->right);
Q.pop();
if (rt->left==NULL && rt->right==NULL) return i;
}
}
return -1; //For the compiler thing. The code never runs here.
}