Is This a Binary Search Tree?

Sort by

recency

|

899 Discussions

|

  • + 0 comments
    Initially, I was failing some test cases but then i changed the condition in inorder function to check for >= instead of > and then it worked. This means that if a node has a parent or a child equal to itself then it voilates the BST property. 
    
    bool inorder(Node* root,vector<int>& vec){
        if(!root){
            return true;
        }
        bool l=inorder(root->left,vec);
        if(vec.size() && vec.back()>=root->data){
            return false;
        }
        vec.push_back(root->data);
        bool r=inorder(root->right,vec);
    
        return l && r;
    
    }
    bool checkBST(Node* root) {
        if(!root){
            return false;
        }
        vector<int> vec;
        if(inorder(root,vec)){
            return true;
        }
    
        return false;
    }
    
  • + 0 comments

    Some of the tests are wrong. The following tree is binary search. But it says that it's not. Thank u for wasting my time :( data 3 data left 2 data right 6 data 2 data left 1 data right 4 data 1 data 4 data 6 data left 5 data right 7 data 5 data 7

  • + 0 comments

    include

    bool isBSTUtil(Node* node, int min, int max) { if (node == nullptr) return true; if (node->data <= min || node->data >= max) return false; return isBSTUtil(node->left, min, node->data) && isBSTUtil(node->right, node->data, max); }

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

  • + 0 comments
    def check_binary_search_tree_(root):
        # create helper function
        def check(root, min_value, max_value):
            # base case
            if root is None:
                return True
            
            # general case
            if root.data < min_value or root.data > max_value:
                return False
            
            return check(root.left, min_value, root.data - 1) and check(root.right, root.data + 1, max_value)
        
        return check(root, 0, 10000)
    
  • + 1 comment
    def inorder_list(root):
        values = []
        def inorder_t(root):
            if root is None:
                return
            inorder_t(root.left)
            values.append(root.data)
            inorder_t(root.right)
        inorder_t(root)
        return values
    
    def check_binary_search_tree_(root):
        if root is None:
            return
        values = inorder_list(root)
        if values == sorted(values) and len(values) == len(set(values)):
            return True
        else:
            return False