-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathChecking is tree BST.cpp
More file actions
104 lines (71 loc) · 1.65 KB
/
Copy pathChecking is tree BST.cpp
File metadata and controls
104 lines (71 loc) · 1.65 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct BSTNode
{
int data;
BSTNode *left;
BSTNode *right;
};
struct BSTNode *GetNewNode(int data)
{
struct BSTNode *NewNode = new BSTNode();
NewNode->data=data;
NewNode->left = NULL ;
NewNode->right = NULL;
return NewNode;
}
struct BSTNode *Insert(BSTNode* root, int data)
{
if(root==NULL)
root= GetNewNode(data);
else if(data <= root->data)
root->left = Insert(root->left , data);
else
root->right = Insert(root->right , data);
return root;
}
bool IsSubtreeLesser(BSTNode *root , int d)
{
if(root==NULL)
return 1;
else if(root->data<=d && IsSubtreeLesser(root->left , d) &&IsSubtreeLesser(root->right , d))
return 1;
else
return 0;
}
bool IsSubtreeGreater(BSTNode *root , int d)
{
if(root==NULL)
return 1;
else if(root->data >d && IsSubtreeGreater(root->left , d) &&IsSubtreeGreater(root->right , d))
return 1;
else
return 0;
}
bool IsBST(BSTNode *root)
{
if(root==NULL)
return 1;
else if(IsSubtreeLesser(root->left , root->data) && IsSubtreeGreater(root->right,root->data) && IsBST(root->left) && IsBST(root->right))
return 1;
else
return 0;
}
int main()
{
struct BSTNode *rootPtr = NULL;
rootPtr = Insert(rootPtr , 5);
rootPtr = Insert(rootPtr , 7);
rootPtr = Insert(rootPtr , 4);
rootPtr = Insert(rootPtr , 15);
rootPtr = Insert(rootPtr , 17);
rootPtr = Insert(rootPtr , 14);
rootPtr = Insert(rootPtr , 11);
if(IsBST(rootPtr))
cout<<"Tree is BST.";
else
cout<<"Tree is not BST.";
return 0;
}