测试树是否为二叉搜索树

时间:2018-08-07 16:33:00

标签: c++ algorithm tree binary-search-tree

我知道我不应该在这里问这些类型的问题,但是我被困住了,无法找出问题所在。所以, 我写了这段代码,它以树的根作为输入,并检查给定的树是否为BST。但是我没有几个测试用例,我不明白为什么?如果有人可以告诉我代码中的错误,将不胜感激。 这是问题Is This a Binary Search Tree?

的链接

这是代码。

bool checkBST(Node* root) {
    if(root == NULL)
        return false;


        int d = root->data;
        bool r1 = true,r2=true;
        if(root->left != NULL){
            if(d < root->left->data)
                r1 = false;
            else
                r1 = checkBST(root->left);

        }

        if(root->right != NULL){
            if(d > root->right->data)
                r2 = false;
            else
                r2 = checkBST(root->right);
        }
        return r1 && r2;

    }

2 个答案:

答案 0 :(得分:1)

为什么不这样:

int checkBST(Node *root, int min, int max) {
  /* an empty tree is BST */
  if (root == NULL)
    return true;

  /* false if this node violates the min/max constraint */
  if (root->data < min || root->data > max)
    return 0;

  /* otherwise check the subtrees recursively, 
   tightening the min or max constraint */
  return
  checkBST(root->left, min, root->data - 1) && // Allow only distinct values
    checkBST(root->right, root->data + 1, max);
}

int checkBST(Node *root) {
    return checkBST(root, INT_MIN, INT_MAX);
}

然后您将这样调用函数:

checkBST(tree)

您的主要问题是您没有跟踪子BST受限的minmax值。另外,null树是BST。

答案 1 :(得分:1)

问题可能是您仅针对每个节点的父节点进行检查。请记住,整个子树必须位于父树的任一侧。

EG

                   10

           4

       2      12

这将通过您的代码。每个孩子相对于其直接父母都是正确的值。但是12比根10大,但是在左子树中。

#include <climits>

bool checkBST(Node* root, int min, int max) {
    if (!root) {return true;}

    return (min <= root->data && root->data <= max)
        && checkBST(root->left, min, root->data-1)
        && checkBST(root->right, root->data+1, max);
}
bool checkBST(Node* root) {
    return checkBST(root, INT_MIN, INT_MAX);
}
相关问题