int isBSTUtil(struct tree* head, int min, int max) { if (head == NULL) return 1; if (head->data < min || head->data > max) return 0; return isBSTUtil(head->left, min, head->data) && isBSTUtil(head->right, head->data, max); }
/*Find if Binary tree is a BST*/ bool isBSTUtil(Node *root, int min, int max) { if(root==NULL) return true; if(root->val<min || root->val>max) return false; else return(isBSTUtil(root->left, min, root->val-1) && isBSTUtil(root->right, root->val+1, max)); }
bool isBSTUtil(struct node* node, int min, int max){ if (NULL == node) return true; // false if this node violates the min/max constraint if (node->data < min || node->data > max) return false; // otherwise check the subtree recrusively return isBSTUtil(node->left, min, node->data) && isBSTUtil(node->right, node->data+1, max); }
int isBSTUtil(Node *root, int min, int max) { if (!root) return 1; if (root->data < min || root->data > max) return 0; return isBSTUtil(root->left, min, root->data - 1) && isBSTUtil(root->right, root->data + 1, max); }
// Method 1: Keeping track of the narrowing min and max allowed values bool isBSTUtil(Node* node, int min, int max) { // Empty tree is BST if (node == NULL) return true; if (node->data < min || node->data > max) return false; return isBSTUtil(node->left, min, node->data - 1) && // Allow only distinct values isBSTUtil(node->right, node->data + 1, max); }
/* Returns true if the given tree is a BST and its values are >= min and <= max. */ int isBSTUtil(struct node* node, int min, int max) { /* an empty tree is BST */ if (node==NULL) return 1; /* false if this node violates the min/max constraint */ if (node->data < min || node->data > max) return 0; /* otherwise check the subtrees recursively, tightening the min or max constraint */ return isBSTUtil(node->left, min, node->data-1) && // Allow only distinct values isBSTUtil(node->right, node->data+1, max); // Allow only distinct values }
int main() { int *arr = (int *)malloc(sizeof(int)*100); Node *root = createBT(); // printPathBT(root,arr, 0); mirrorBT(root); printTree(root); printf("\nisBST=%d", (int)isBSTUtil(root, INT_MIN, INT_MAX)); return 0; }
/* * Return true if the binary tree is BST (efficient version) */ bool isBST_e(struct node* node){ return isBSTUtil(node, INT_MIN, INT_MAX); }
int isBST(struct tree* head) { return isBSTUtil(head, minValue(head), maxValue(head)); }
/* Returns true if the given tree is a binary search tree (efficient version). */ int isBST(struct node* node) { return(isBSTUtil(node, INT_MIN, INT_MAX)); }
bool isBST(Node* root) { return isBSTUtil(root, INT_MIN, INT_MAX); }