Created
August 6, 2019 09:15
-
-
Save ajinkyajawale14499/8df4c276c2a91fc8d71b2c3caefb1906 to your computer and use it in GitHub Desktop.
Check if binary tree is BST or not.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<bits/stdc++.h> | |
using namespace std; | |
class node{ | |
public: int data; | |
node* left; | |
node* right; | |
node(int data) | |
{ | |
this->data = data; | |
this->left = NULL; | |
this->right = NULL; | |
} | |
}; | |
int isBST(node* root){ | |
static node *prev = NULL; | |
// traverse the tree in inorder fashion and keep track of prev node | |
if (root) | |
{ | |
if (!isBST(root->left)) | |
return 0; | |
// Allows only distinct valued nodes | |
if (prev != NULL && root->data <= prev->data) | |
return 0; | |
prev = root; | |
return isBST(root->right); | |
} | |
return true; | |
} | |
int main() | |
{ | |
node* root = new node(4); | |
root->left = new node(2); | |
root->right = new node(5); | |
root->left->right = new node(1); | |
root->left->right=new node(3); | |
if(isBST(root)) | |
cout<<"is BST"; | |
else cout<<"is not BST"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment