我的方法是BFS做的,当然这个题目也可以采用递归的方法来做。
- 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) {
int mindep=0;
if(root==nullptr)
return mindep;
queue<TreeNode*>que;
que.push(root);
int k=1;
mindep=100000000;
while(!que.empty())
{
vector<TreeNode*>vec;
while(!que.empty())
{
root=que.front();
que.pop();
if(root->left==nullptr&&root->right==nullptr)
mindep=min(mindep,k);
if(root->left)vec.push_back(root->left);
if(root->right)vec.push_back(root->right);
}
k++;
for(int i=0;i<vec.size();i++)
{
que.push(vec[i]);
}
}
return mindep;
}
};
- 递归
/**
* 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) {
int result=func(root);
return result;
}
int func(TreeNode* root)
{
if(root==nullptr)
return 0;
if(root->left==nullptr&&root->right==nullptr)
return 1;
int mind=9999999;
if(root->left!=nullptr)
mind=min(mind,func(root->left));
if(root->right!=nullptr)
mind=min(mind,func(root->right));
return mind+1;
}
};