We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// 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);
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Trees: Is This a Binary Search Tree?
You are viewing a single comment's thread. Return to all 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; }
}
// Function to check if a tree is a BST bool checkBST(Node* root) { return checkBSTUtil(root, LONG_MIN, LONG_MAX); }