int checkBST(node *root, int min, int max) { if(root == 0) return 1; if(root->value > max || root->value < min) return 0; return (checkBST(root->left, min, root->value) && checkBST(root->right, root->value, max)); }
bool checkBST(TreeNode<T>* node) { // value of left child must be less, value of the right one must be greater if (node->left) { if (node->left->value >= node->value) return false; if (!checkBST(node->left)) return false; } if (node->right) { if (node->right->value < node->value) return false; if (!checkBST(node->right)) return false; } return true; }
int checkBST(element *root, int left, int right) { element *ele = root; if(!ele) return 1; return (ele->data > left && ele->data < right && checkBST(ele->left, left, ele->data) && checkBST(ele->right, ele->data, right)); }
main() { element *root = makeNode(50); root->left = makeNode(25); root->right = makeNode(75); root->left->right = makeNode(60); printf("%d\n", checkBST(root, INT_MIN, INT_MAX)); }
void ex4_5() { std::cout << "ex4.5 \n"; std::vector<int> in; for (int sample = 0; sample < std::rand() % 10000; ++sample) in.push_back(std::rand() % 20); std::sort(in.begin(), in.end()); auto node = createBST(in, 0, (int) in.size()) ; // std::cout << " sample size=" << in.size() << ", max height = " << height << ", log(size)=" << log2(in.size()) << std::endl; std::cout << "is it a BST? " << checkBST(node); }
int checkBST(TreeNode *root, int min, int max) { if (root == NULL) { return 0; } if ((root->val < min) || (root->val > max)) { return -1; } int left = checkBST(root->left, min, root->val); int right = checkBST(root->right, root->val, max); if (left == -1 || right == -1) { return -1; } return 1 + left + right; }
void main() { node *root,*newroot; root = getNode(4); root->left = getNode(2); root->right = getNode(5); root->left->left = getNode(1); root->left->right = getNode(3); // global max and min int printf("%s",checkBST(root,-32767,32767)?"true":"false"); newroot = getNode(3); newroot->left = getNode(2); newroot->right = getNode(5); newroot->left->left = getNode(1); newroot->left->right = getNode(4); // global max and min int printf("%s",checkBST(newroot,-32767,32767)?"true":"false"); }
void maxsub_BST_helper(TreeNode *root, int &res) { if (root == NULL) { return; } int ret = checkBST(root, INT_MIN, INT_MAX); if ( ret != -1) { if(ret > res) { res = ret; } return; } maxsub_BST_helper(root->left, res); maxsub_BST_helper(root->right, res); }