-
Notifications
You must be signed in to change notification settings - Fork 508
/
Copy pathCheck for BST.cpp
74 lines (64 loc) · 1.44 KB
/
Check for BST.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
/*
Check for BST
=============
Given a binary tree. Check whether it is a BST or not.
Note: We are considering that BSTs can not contain duplicate Nodes.
Example 1:
Input:
2
/ \
1 3
Output: 1
Explanation:
The left subtree of root node contains node
with key lesser than the root node’s key and
the right subtree of root node contains node
with key greater than the root node’s key.
Hence, the tree is a BST.
Example 2:
Input:
2
\
7
\
6
\
5
\
9
\
2
\
6
Output: 0
Explanation:
Since the node with value 7 has right subtree
nodes with keys less than 7, this is not a BST.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isBST() which takes the root of the tree as a parameter and returns true if the given binary tree is BST, else returns false.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
0 <= Number of edges <= 100000
*/
bool isBST(Node *root)
{
if (!root)
return true;
bool ans = true;
ans = isBST(root->left) && isBST(root->right);
auto left = root->left, right = root->right;
if (left)
{
while (left->right)
left = left->right;
ans = ans && (left->data < root->data);
}
if (right)
{
while (right->left)
right = right->left;
ans = ans && (right->data > root->data);
}
return ans;
}