check if a tree is a binary search tree

前端 未结 9 1005
遥遥无期
遥遥无期 2021-01-30 09:29

I have written the following code to check if a tree is a Binary search tree. Please help me check the code:

Okay! The code is edited now. This simple solution was sugge

9条回答
  •  萌比男神i
    2021-01-30 09:52

    A binary search tree has the following properties where the key for the left node must be <= the root node key and the right node key must be greater that the root.

    So the problem we have is if the keys in the tree are not unique and a in order traversal was done we could get a situation of two in order traversals producing the same sequence, where 1 would be a valid bst and the other would not, this would happen if we had a tree where the left node = root(valid bst) and the right node = root(invalid not a bst).

    To get around this we need to maintain a valid min/max range that the key being 'visited' must fall between, and we pass this range as we recurse to other nodes.

    #include 
    
    int min = numeric_limits::min();
    int max = numeric_limits::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;
    }
    

提交回复
热议问题