From 52d1c3e421abf27f9e316eba43fff9c6302ed4cd Mon Sep 17 00:00:00 2001 From: Masoom9587 <93204893+Masoom9587@users.noreply.github.com> Date: Fri, 21 Oct 2022 12:03:19 +0530 Subject: [PATCH] code for binary tree is a bst or not!! solved the issue #250 --- tree.cpp | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 tree.cpp diff --git a/tree.cpp b/tree.cpp new file mode 100644 index 00000000..ef19d662 --- /dev/null +++ b/tree.cpp @@ -0,0 +1,60 @@ +// C++ program to check if a given tree is BST. +#include +using namespace std; + +/* A binary tree node has data, pointer to +left child and a pointer to right child */ +struct Node { + int data; + struct Node *left, *right; + + Node(int data) + { + this->data = data; + left = right = NULL; + } +}; + +bool isBSTUtil(struct Node* root, Node*& prev) +{ + // traverse the tree in inorder fashion and + // keep track of prev node + if (root) { + if (!isBSTUtil(root->left, prev)) + return false; + + // Allows only distinct valued nodes + if (prev != NULL && root->data <= prev->data) + return false; + + prev = root; + + return isBSTUtil(root->right, prev); + } + + return true; +} + +bool isBST(Node* root) +{ + Node* prev = NULL; + return isBSTUtil(root, prev); +} + +/* Driver code*/ +int main() +{ + struct Node* root = new Node(3); + root->left = new Node(2); + root->right = new Node(5); + root->left->left = new Node(1); + root->left->right = new Node(4); + + // Function call + if (isBST(root)) + cout << "Is BST"; + else + cout << "Not a BST"; + + return 0; +}