typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
#include <stdio.h>
#include <limits.h>
int isBSTUtil(Node* root, int min, int max) {
if (root == NULL) return 1;
if (root->data <= min || root->data >= max) return 0;
return isBSTUtil(root->left, min, root->data) && isBSTUtil(root->right, root->data, max);
}
int isBST(Node* root) {
return isBSTUtil(root, INT_MIN, INT_MAX);
}
int main() {
Node n1 = {10, NULL, NULL};
Node n2 = {5, NULL, NULL};
Node n3 = {15, NULL, NULL};
Node n4 = {3, NULL, NULL};
Node n5 = {7, NULL, NULL};
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
printf("%d\n", isBST(&n1));
return 0;
}The tree is a valid BST because every node's value is within the allowed range defined by its ancestors.
The function returns 1 indicating true.
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
#include <stdio.h>
#include <limits.h>
int isBSTUtil(Node* root, int min, int max) {
if (root == NULL) return 1;
if (root->data <= min || root->data >= max) return 0;
return isBSTUtil(root->left, min, root->data) && isBSTUtil(root->right, root->data, max);
}
int isBST(Node* root) {
return isBSTUtil(root, INT_MIN, INT_MAX);
}
int main() {
Node n1 = {10, NULL, NULL};
Node n2 = {5, NULL, NULL};
Node n3 = {8, NULL, NULL};
Node n4 = {3, NULL, NULL};
Node n5 = {12, NULL, NULL};
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5; // Incorrect placement
printf("%d\n", isBST(&n1));
return 0;
}The node with value 12 is in the left subtree of 10, which violates the BST property.
The function returns 0 indicating false.
The min and max values define the valid range for each node's value to maintain BST ordering.
int isBSTUtil(Node* root, int min, int max) { if (root == NULL) return 1; if (root->data < min || root->data > max) return 0; return isBSTUtil(root->left, min, root->data) && isBSTUtil(root->right, root->data, max); }
BST does not allow duplicate values on the same side, so <= and >= are needed to reject equal values.
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Assume helper functions and structs are defined
int largestBSTSubtree(Node* root) {
// Implementation omitted
return 0;
}
int main() {
Node n1 = {10, NULL, NULL};
Node n2 = {5, NULL, NULL};
Node n3 = {15, NULL, NULL};
Node n4 = {1, NULL, NULL};
Node n5 = {8, NULL, NULL};
Node n6 = {7, NULL, NULL};
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
n3.left = &n6;
printf("%d\n", largestBSTSubtree(&n1));
return 0;
}The largest BST subtree includes nodes 5, 1, 8, and 7 is invalid because 7 is in right subtree of 15 but less than 15.
The largest valid BST subtree is rooted at node 5 with nodes 5, 1, and 8.
