From c1b0d455bff54592a1e7aa87810af0a9a670fcfd Mon Sep 17 00:00:00 2001 From: Ijlal Ahmad Date: Sat, 8 Oct 2022 16:22:24 +0530 Subject: [PATCH] added validate binary search tree algorithm --- algorithms/CPlusPlus/README.md | 1 + .../Trees/validate-binary-search-tree.cpp | 60 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/validate-binary-search-tree.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 1de7183a..e73b758c 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -152,6 +152,7 @@ - [Iterative Segment Tree](Trees/IterativeSegmentTree.cpp) - [Print all nodes at level k](Trees/print-all-nodes-at-a-level.cpp) - [Sum of right leaves](Trees/sum-of-right-leaves.cpp) +- [Validate Binary Search Tree](Trees/validate-binary-search-tree.cpp) ## Trie diff --git a/algorithms/CPlusPlus/Trees/validate-binary-search-tree.cpp b/algorithms/CPlusPlus/Trees/validate-binary-search-tree.cpp new file mode 100644 index 00000000..4b996e49 --- /dev/null +++ b/algorithms/CPlusPlus/Trees/validate-binary-search-tree.cpp @@ -0,0 +1,60 @@ +#include +using namespace std; + +// sturcture of a tree node +struct Node +{ + int data; + Node *right; + Node *left; + + Node(int data) + { + this->data = data; + this->right = NULL; + this->left = NULL; + } +}; + +// function to check if a tree is a BST or not +bool validateBST(Node *root) +{ + // if the tree is empty + if (root == NULL) + return true; + + // if the left child is not null and its data is greater than the root's data then its not a BST + if (root->left != NULL && root->left->data > root->data) + return false; + + // if the right child is not null and its data is less than the root's data then its not a BST + if (root->right != NULL && root->right->data < root->data) + return false; + + // if the left and right subtree are not BST then the tree is not a BST + if (!validateBST(root->left) || !validateBST(root->right)) + return false; + + // if all the above conditions are false then the tree is a BST + return true; +} + +int main() +{ + // creating a bst + Node *root = new Node(5); + root->left = new Node(3); + root->right = new Node(7); + root->left->left = new Node(2); + root->left->right = new Node(4); + root->right->left = new Node(6); + root->right->right = new Node(8); + + // checking if the tree is a BST or not + if (validateBST(root)) + cout << "Valid BST" << endl; + else + cout << "Invalid BST" << endl; + + return 0; +} \ No newline at end of file