您的位置:首页 > 其它

leetcode 111:Minimum Depth of Binary Tree

2017-05-27 10:29 435 查看
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.
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 BFS DFS 递归