为什么即使输入是BST,也打印“否,不是BST”?

时间:2020-05-23 12:03:43

标签: pointers recursion binary-tree binary-search-tree nodes

我试图编写一些代码来检查输入树是否是二进制搜索树。 但是,我发现即使输入树是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;
}

0 个答案:

没有答案
相关问题