检查一棵树是否为二叉搜索树。

28

我编写了下面的代码来检查一棵树是否为二叉搜索树。请帮忙检查一下代码:

好的!代码现在已经被编辑过了。这个简单的解决方案是在下面的帖子中由某人提出的:

IsValidBST(root,-infinity,infinity);

bool IsValidBST(BinaryNode node, int MIN, int MAX) 
{
     if(node == null)
         return true;
     if(node.element > MIN 
         && node.element < MAX
         && IsValidBST(node.left,MIN,node.element)
         && IsValidBST(node.right,node.element,MAX))
         return true;
     else 
         return false;
}

@TimeToCodeTheRoad - 这是用什么语言编写的?如果您编辑问题并适当标记您的问题,那将非常有帮助。此外,您应该使用代码标记按钮({})来格式化您的代码以便更易于阅读。最后,您的代码有什么问题?我们到底在“检查”什么,您是否遇到错误? - LittleBobbyTables - Au Revoir
这是Java代码,我正在检查一个BinaryNode v是否满足二叉搜索树的属性。 - TimeToCodeTheRoad
3
@TimeToCodeTheRoad - 我刚刚开了一个玩笑 :) 你可能知道谁是Bobby Tables - http://xkcd.com/327/ :) - Petar Minchev
@TimeToCode,我认为你这样做只能得到整个树的“Min”和“Max”,而不是每个子树的。 - user418748
2
如果树中存在重复的条目怎么办?它不应该是<= Max和>= Min吗? - Henley
显示剩余10条评论
9个回答

11

这种方法在某些测试用例中会失败。虽然看起来很酷,但不要采用这种解决方案。请查看此处的答案:https://metamug.com/blog/common-binary-tree-questions-java,以及相关的二叉树问题。 - Sorter

5
一个方法应该一次只做一件事情。而且你所做的方式通常很奇怪。 我会给你一些类似Java的伪代码。对此我很抱歉,因为我已经有一段时间没有接触Java了。希望这可以帮到你。看看我在问题上的注释,希望你能解决它! 像这样调用你的isBST:
public boolean isBst(BNode node)
{
    return isBinarySearchTree(node , Integer.MIN_VALUE , Integer.MIN_VALUE);
}

内部实现:

public boolean isBinarySearchTree(BNode node , int min , int max)
{
    if(node.data < min || node.data > max)
        return false;
    //Check this node!
    //This algorithm doesn't recurse with null Arguments.
    //When a null is found the method returns true;
    //Look and you will find out.
    /*
     * Checking for Left SubTree
     */
    boolean leftIsBst = false;
    //If the Left Node Exists
    if(node.left != null)
    {
        //and the Left Data are Smaller than the Node Data
        if(node.left.data < node.data)
        {
            //Check if the subtree is Valid as well
            leftIsBst = isBinarySearchTree(node.left , min , node.data);
        }else
        {
            //Else if the Left data are Bigger return false;
            leftIsBst = false;
        }
    }else //if the Left Node Doesn't Exist return true;
    {
        leftIsBst = true;
    }

    /*
     * Checking for Right SubTree - Similar Logic
     */
    boolean rightIsBst = false;
    //If the Right Node Exists
    if(node.right != null)
    {
        //and the Right Data are Bigger (or Equal) than the Node Data
        if(node.right.data >= node.data)
        {
            //Check if the subtree is Valid as well
            rightIsBst = isBinarySearchTree(node.right , node.data+1 , max);
        }else
        {
            //Else if the Right data are Smaller return false;
            rightIsBst = false;
        }
    }else //if the Right Node Doesn't Exist return true;
    {
        rightIsBst = true;
    }

    //if both are true then this means that subtrees are BST too
    return (leftIsBst && rightIsBst);
}

现在:如果你想要找到每个子树的最小值和最大值,你应该使用一个容器(我使用了一个ArrayList),并存储一个三元组,它表示根节点和相应的值(显然)。
例如:
/*
 * A Class which is used when getting subTrees Values
 */
class TreeValues
{
    BNode root; //Which node those values apply for
    int Min;
    int Max;
    TreeValues(BNode _node , _min , _max)
    {
        root = _node;
        Min = _min;
        Max = _max;
    }
}

并且:

/*
 * Use this as your container to store Min and Max of the whole
 */
ArrayList<TreeValues> myValues = new ArrayList<TreeValues>;

现在这是一种方法,用于查找给定节点的最小值最大值:

/*
 * Method Used to get Values for one Subtree
 * Returns a TreeValues Object containing that (sub-)trees values
 */ 
public TreeValues GetSubTreeValues(BNode node)
{
    //Keep information on the data of the Subtree's Startnode
    //We gonna need it later
    BNode SubtreeRoot = node;

    //The Min value of a BST Tree exists in the leftmost child
    //and the Max in the RightMost child

    int MinValue = 0;

    //If there is not a Left Child
    if(node.left == null)
    {
        //The Min Value is this node's data
        MinValue = node.data;
    }else
    {
        //Get me the Leftmost Child
        while(node.left != null)
        {
            node = node.left;
        }
        MinValue = node.data;
    }
    //Reset the node to original value
    node = SubtreeRoot; //Edit - fix
    //Similarly for the Right Child.
    if(node.right == null)
    {
        MaxValue = node.data;
    }else
    {
        int MaxValue = 0;
        //Similarly
        while(node.right != null)
        {
            node = node.right;
        }
        MaxValue = node.data;
    }
    //Return the info.
    return new TreeValues(SubtreeRoot , MinValue , MaxValue);   
}

但是这只返回一个节点的值,所以我们将使用它来查找整个树:
public void GetTreeValues(BNode node)
{
    //Add this node to the Container with Tree Data 
    myValues.add(GetSubTreeValues(node));

    //Get Left Child Values, if it exists ...
    if(node.left != null)
        GetTreeValues(node.left);
    //Similarly.
    if(node.right != null)
        GetTreeValues(node.right);
    //Nothing is returned, we put everything to the myValues container
    return; 
}

使用这些方法,您的调用应该如下所示:
if(isBinarySearchTree(root))
    GetTreeValues(root);
//else ... Do Something

这几乎是Java。只需要进行一些修改和修复就可以运行。找一本好的面向对象编程书籍,它会对你有所帮助。请注意,这个解决方案可以拆分成更多的方法。


@Muggen:我认为你检查isBST()的方法是错误的。在这棵树上试一试:根节点为10,然后根节点的子节点是9和12。然后9的子节点是8和40。这不是BST,但是你的代码却说它是!如果你同意,请给我一些信用并移除-1。 - TimeToCodeTheRoad
@TimeToCode,哪一个是根? - user418748
@TimeToCode,如果我一开始就清楚知道你想要做什么,我会做得更好。尝试从一开始就给出例子。 - user418748
1
@Muggen:是的,现在看起来没问题了 :). 我假设对于左子树,你调用isBST(v.left, min, v.data)。感谢您的建议。下次我一定会给更多的例子。感谢您的时间和耐心。此外,对于右子树,我认为isBST(v.right, v.data, max)也可以工作。总体而言,您的逻辑似乎很酷,而且相当直接。再次感谢您的帮助。非常感激。 - TimeToCodeTheRoad
@TimeToCode,没问题。玩得开心! - user418748
显示剩余3条评论

5
boolean bst = isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);

public boolean isBST(Node root, int min, int max) {
    if(root == null) 
        return true;

    return (root.data > min &&
            root.data < max &&
            isBST(root.left, min, root.data) &&
            isBST(root.right, root.data, max));
    }

4

更新:我刚刚看到此解决方案之前已经被建议过了。抱歉,也许仍然有人会发现我的版本有用。

这里提供一个解决方案,使用中序遍历来检查BST属性。 在提供解决方案之前,请注意我使用的BST定义不允许有重复项。这意味着BST中的每个值都是独特的(只是为了简单起见)。

递归中序打印的代码:

void printInorder(Node root) {
    if(root == null) {                 // base case
        return;
    }
    printInorder(root.left);           // go left
    System.out.print(root.data + " "); // process (print) data
    printInorder(root.right);          // go right
}

在对BST执行中序遍历之后,所有数据都应按升序打印出来。例如,这棵树:
   5
 3   7
1 2 6 9

需要打印的内容:

如果按顺序打印,应该是:
1 2 3 5 6 7 9

现在,我们可以记录中序遍历序列中的上一个节点值,并将其与当前节点的值进行比较,而不是打印该节点。如果当前节点的值小于前一个值,则意味着该序列不是按升序排序的,违反了BST属性。
例如,树如下:
   5
 3   7
1 8 6 9

存在违规情况。节点3的右子节点是8,如果3是根节点,那么这样做是可以的。但在二叉搜索树中,8将成为9的左子节点而不是3的右子节点。因此,该树不是二叉搜索树。

因此,代码应按照以下思路编写:

/* wrapper that keeps track of the previous value */
class PrevWrapper {
    int data = Integer.MIN_VALUE;
}

boolean isBST(Node root, PrevWrapper prev) {
    /* base case: we reached null*/
    if (root == null) {
        return true;
    }

    if(!isBST(root.left, prev)) {
        return false;
    }
    /* If previous in-order node's data is larger than
     * current node's data, BST property is violated */
    if (prev.data > root.data) {
        return false;
    }

    /* set the previous in-order data to the current node's data*/
    prev.data = root.data;

    return isBST(root.right, prev);
}

boolean isBST(Node root) {
    return isBST(root, new PrevWrapper());
}

样例树的中序遍历会因为节点5而失败,因为5的前一个中序是8,它更大,违反了二叉搜索树的性质。

1
很好,你检查了之前是否有答案,并在开头标记了它(即使晚了几分钟:-)。 - greybeard

2
    boolean isBST(TreeNode root, int max, int min) {
        if (root == null) {
            return true;
        } else if (root.val >= max || root.val <= min) {
            return false;
        } else {
            return isBST(root.left, root.val, min) && isBST(root.right, max, root.val);
        }

    }

一种解决这个问题的替代方法...与你的代码类似。

1
一棵二叉搜索树具有以下属性:左节点的键必须<=根节点键,右节点键必须大于根节点。因此,如果树中的键不是唯一的,并且进行了顺序遍历,我们可能会得到两个顺序遍历产生相同序列的情况,其中一个将是有效的bst,而另一个则不是。这种情况发生在左节点=根(有效的bst)和右节点=根(无效的非bst)的树中。为了解决这个问题,我们需要维护一个有效的最小/最大范围,被“访问”的键必须落在这个范围内,并且我们将这个范围作为我们递归到其他节点的参数传递。
#include <limits>

int min = numeric_limits<int>::min();
int max = numeric_limits<int>::max();

The calling function will pass the above min and max values initially to isBst(...)

bool isBst(node* root, int min, int max)
{
    //base case
    if(root == NULL)
        return true;

    if(root->val <= max && root->val >= min)
    {
        bool b1 = isBst(root->left, min, root->val);
        bool b2 = isBst(root->right, root->val, max);
        if(!b1 || !b2)
            return false;
        return true;
    }
    return false;
}

0
我们通过深度优先遍历树,一边遍历一边测试每个节点的有效性。如果给定节点大于其所在右子树中所有祖先节点且小于其所在左子树中所有祖先节点,则该节点是有效的。为了避免跟踪每个祖先以检查这些不等式,我们只需检查它必须大于的最大数字(其下限)和它必须小于的最小数字(其上限)。
 import java.util.Stack;

final int MIN_INT = Integer.MIN_VALUE;
final int MAX_INT = Integer.MAX_VALUE;

public class NodeBounds {

BinaryTreeNode node;
int lowerBound;
int upperBound;

public NodeBounds(BinaryTreeNode node, int lowerBound, int upperBound) {
    this.node = node;
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
}
}

public boolean bstChecker(BinaryTreeNode root) {

// start at the root, with an arbitrarily low lower bound
// and an arbitrarily high upper bound
Stack<NodeBounds> stack = new Stack<NodeBounds>();
stack.push(new NodeBounds(root, MIN_INT, MAX_INT));

// depth-first traversal
while (!stack.empty()) {
    NodeBounds nb = stack.pop();
    BinaryTreeNode node = nb.node;
    int lowerBound = nb.lowerBound;
    int upperBound = nb.upperBound;

    // if this node is invalid, we return false right away
    if ((node.value < lowerBound) || (node.value > upperBound)) {
        return false;
    }

    if (node.left != null) {
        // this node must be less than the current node
        stack.push(new NodeBounds(node.left, lowerBound, node.value));
    }
    if (node.right != null) {
        // this node must be greater than the current node
        stack.push(new NodeBounds(node.right, node.value, upperBound));
    }
}

// if none of the nodes were invalid, return true
// (at this point we have checked all nodes)
return true;
}

0
public void inorder()
     {
         min=min(root);
         //System.out.println(min);
         inorder(root);

     }

     private int min(BSTNode r)
         {

             while (r.left != null)
             {
                r=r.left;
             }
          return r.data;


     }


     private void inorder(BSTNode r)
     {

         if (r != null)
         {
             inorder(r.getLeft());
             System.out.println(r.getData());
             if(min<=r.getData())
             {
                 System.out.println(min+"<="+r.getData());
                 min=r.getData();
             }
             else
             System.out.println("nananan");
             //System.out.print(r.getData() +" ");
             inorder(r.getRight());
             return;
         }
     }

0

将INTEGER.MIN和INTEGER.MAX作为空树的返回值并不是很合理。也许可以使用Integer类型,然后返回null。


@anonymous:为什么是-1,请解释一下,因为这是不可接受的。我正在努力做好这件事,而你只是给了一个-1。 - TimeToCodeTheRoad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接