递归:
int minDepth(TreeNode *root) {
// write your code here
if (root == NULL)
{
return 0;
}
if (root->left == NULL && root->right == NULL)
{
return 1;
}
if (root->left == NULL)
{
return 1 + minDepth(root->right);
}
else if (root->right == NULL)
{
return 1 + minDepth(root->left);
}
else
{
int left = minDepth(root->left);
int right = minDepth(root->right);
return 1 + min(left, right);
}
}
非递归:
int minDepth(TreeNode *root) {
// write your code here
if(root==NULL)
return 0;
list<int> l2;
list<TreeNode *> l1;
l1.push_back(root);
l2.push_back(1);
while(true)
{
TreeNode* tem=l1.front();
int res=l2.front();
if(tem->left==NULL&&tem->right==NULL)
{
return res;
}
l1.erase(l1.begin());
l2.erase(l2.begin());
if(tem->left!=NULL)
{
l1.push_back(tem->left);
l2.push_back(res+1);
}
if(tem->right!=NULL)
{
l1.push_back(tem->right);
l2.push_back(res+1);
}
}
}