簡體   English   中英

檢查樹是否是二叉搜索樹

[英]check if a tree is a binary search tree

我編寫了以下代碼來檢查樹是否是二進制搜索樹。 請幫我查一下代碼:

好的! 代碼現在已編輯。 以下帖子中有人建議使用這個簡單的解決方案:

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;
}

對,另一個簡單的解決方案是進行一次訪問

java代碼在這里

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));
    }

方法一次只能做一件事。 你做事的方式通常也很奇怪。 我會給你一些幾乎是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);
}

現在:如果要查找每個子樹的MinMax ,則應使用Container(我使用ArrayList )並存儲Node, Min, Max的三元組Node, Min, Max它表示根節點和值(顯然)。

例如。

/*
 * 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>;

現在,這是一個查找給定節點的MinMax值的方法:

/*
 * 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);   
}

但是這只返回一個Node的值,所以我們將使用它來查找Whole Tree:

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。 它應該與一些修改和修復工作。 找一本好的OO書,它會對你有幫助。 請注意,此解決方案可以分解為更多方法。

更新:我剛剛看到此解決方案之前已被建議。 對這些家伙感到抱歉,也許有人仍覺得我的版本很有用

這是一個使用In-Order Traversal檢查BST屬性的解決方案。 在我提供解決方案之前,我使用的是不允許重復的BST定義。 這意味着BST中的每個值都是唯一的(這只是為了簡單起見)。

遞歸inorder打印代碼:

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是根節點,這將是正常的。 然而,在BST 8中 ,最終將成為9的左孩子而不是3的右孩子。 因此,這棵樹不是BST。 那么,遵循這個想法的代碼:

/* 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 ,這更大,因此違反了BST屬性。

    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而另一個不會,如果我們有一個樹,其中左節點= root(有效bst),右節點= root(無效而不是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;
}
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;
         }
     }

我們在樹中進行深度優先遍歷,測試每個節點的有效性。 如果給定節點大於它在右子樹中的所有祖先節點並且少於它在左子樹中的所有祖先節點,則該節點是有效的。 我們只是檢查它必須大於(它的lowerBound)的最大數字和它必須小於(它的upperBound)的最小數字,而不是跟蹤每個祖先來檢查這些不等式。

 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;
}

將INTEGER.MIN,INTEGER.MAX作為空樹的值返回並沒有多大意義。 也許使用Integer並返回null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM