Trees: Is This a Binary Search Tree?

  • + 0 comments

    include // for INT_MIN and INT_MAX

    // Helper function to check the BST condition bool checkBSTUtil(Node* root, long long minVal, long long maxVal) { // Base case: If the node is null, it's a valid BST by definition if (root == nullptr) { return true; }

    // Check if the current node's value is within the valid range
    if (root->data <= minVal || root->data >= maxVal) {
        return false;
    }
    
    // Recursively check the left and right subtrees
    return checkBSTUtil(root->left, minVal, root->data) && 
           checkBSTUtil(root->right, root->data, maxVal);
    

    }

    // Function to check if a tree is a BST bool checkBST(Node* root) { return checkBSTUtil(root, LONG_MIN, LONG_MAX); }