我试图编写一些代码来检查输入树是否是二进制搜索树。 但是,我发现即使输入树是BST,输出也是“否(树不是BST)” 我想知道为什么。我的check_bst可能有问题,但我找不到问题。 所以我在这里还有另外两种方法find_max和find_min,也许这两种方法也有问题。
int find_max(Node* root)
{
int max = 0;
if(root != NULL)
{
if(root->key > max)
{
max = root->key;
}
if(root->left != NULL && root->right != NULL)
{
if(find_max(root->left) >= find_max(root->right))
{
max = find_max(root->left);
}else{
max = find_max(root->right);
}
}else if(root->left == NULL && root->right != NULL)
{
max = find_max(root->right);
}else if(root->left != NULL && root->right == NULL)
{
max = find_max(root->left);
}
}
return max;
}
int find_min(Node* root)
{
int min = 0;
if(root != NULL)
{
if(root->key < min)
{
min = root->key;
}
if(root->left != NULL && root->right != NULL)
{
if(find_min(root->left) <= find_min(root->right))
{
min = find_min(root->left);
}else{
min = find_min(root->right);
}
}else if(root->left == NULL && root->right != NULL)
{
min = find_min(root->right);
}else if(root->left != NULL && root->right == NULL)
{
min = find_min(root->left);
}
}
return min;
}
int check_bst(Node* root)
{
if(root != NULL)
{
if(root->left != NULL)
{
if(find_max(root->left) >= root->key)
{
printf("No(the tree is not BST)");
return false;
}
}
if(root->right != NULL)
{
if(find_min(root->right) <= root->key)
{
printf("No(the tree is not BST)");
return false;
}
}
if(check_bst(root->left) == false || check_bst(root->right) == false)
{
printf("No(the tree is not BST)");
return false;
}
}else{
printf("Yes(the tree is BST)");
return true;
}
printf("Yes(the tree is BST)");
return true;
}