-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_binaryhtree.cpp
89 lines (71 loc) · 2.16 KB
/
check_binaryhtree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Check if the binary tree is a binary serach tree ( BST)
// binary serach tree :
// - left subtree of a node contains only nodes with keys < node’s key.
// - right subtree of a node contains only nodes with keys > node’s key.
//
// Created by @altanai on 31/03/21.
//
#include <iostream>
#include <climits>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
node(int val){
data = val;
left = NULL;
right = NULL;
}
};
// approach 1 :
// assumes no duplicate elements with value INT_MIN or INT_MAX
bool isBST(struct node* root, int min , int max){
// empty free is BST
if(root == NULL) return true;
// not BST if this node violates the min/max constraint
if(root->data < min || root->data > max) return false;
// recisively check for iBST on left-subtree and-right subtree
return isBST(root->left, INT_MIN, root->data-1) && isBST(root->right, root->data+1, INT_MAX);
}
// ----------------------- utility function start
void printBT(const std::string& prefix, const struct node* root, bool isLeft){
if( root != nullptr ){
std::cout << prefix;
std::cout << (isLeft ? "├──" : "└──" );
std::cout << root->data << std::endl;
printBT( prefix + (isLeft ? "│ " : " "), root->left, true);
printBT( prefix + (isLeft ? "│ " : " "), root->right, false);
}
}
void printBT(const struct node* root){
printBT("", root, false);
}
int main(){
// Non BST
// struct node* root = new node(1);
// root->left = new node(2);
// root->right = new node(3);
// root->left->left = new node(4);
// BST
struct node* root = new node(5);
root->left = new node(1);
root->right = new node(7);
printBT(root);
isBST(root,INT_MIN, INT_MAX)? cout<< " Yes it is BST" : cout << " Not a BST" ;
cout << endl ;
return 0;
}
// g++ check_binaryhtree.cpp -o checkbst.out
// ./checkbst.out
// Output for non BST
// └──1
// ├──2
// │ ├──4
// └──3
// Not a BST
// Output for BST
// └──5
// ├──1
// └──7
// Yes it is BST