找树的最小深度。
两种方法:
1、递归
2、BFS
class Solution {
public:
int minDepth(TreeNode* root)
{
//way-1
/*
int mindeep;
if(!root)
return 0;
else if (!root->left && !root->right)
return 1;
else if (!root->left)
mindeep = minDepth(root->right) + 1;
else if (!root->right)
mindeep = minDepth(root->left) + 1;
else
mindeep = min( minDepth(root->left), minDepth(root->right) ) + 1;
return mindeep;
*/
//way-2
int ret = 0;
queue<TreeNode*> que;
if (root)
que.push(root);
while (!que.empty())
{
int size = que.size();
ret++;
for (int i = 0 ; i < size; i++)
{
TreeNode *p = que.front();
if ( !p->left && !p->right )
return ret;
que.pop();
if (p->left)
que.push(p->left);
if (p->right)
que.push(p->right);
}
}
return ret;
}
};