-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCHECKBST.java
More file actions
73 lines (66 loc) · 1.73 KB
/
CHECKBST.java
File metadata and controls
73 lines (66 loc) · 1.73 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
/*Given the root of a binary tree. Check whether it is a BST or not.
Note: We are considering that BSTs can not contain duplicate Nodes.
A BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Examples:
Input:
2
/ \
1 3
\
5
Output: true
Explanation:
The left subtree of every node contains smaller keys and right subtree of every node contains greater. Hence, the tree is a BST.
Input:
2
\
7
\
6
\
9
Output: false
Explanation:
Since the node with value 7 has right subtree nodes with keys less than 7, this is not a BST.
Input:
10
/ \
5 20
/ \
9 25
Output: false
Explanation: The node is present in the right subtree of 10, but it is smaller than 10.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(Height of the tree)
where n is the number of nodes in the given tree
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 105 */
class Solution {
// Function to check whether a Binary Tree is BST or not.
boolean isBST(Node root) {
ArrayList<Integer>node=new ArrayList<>();
check(root,node);
for(int i=0;i<node.size()-1;i++)
{
if(node.get(i) >= node.get(i+1))
{
return false;
}
}
return true;
}
void check(Node root,ArrayList<Integer>node)
{
if(root==null)
{
return;
}
check(root.left,node);
node.add(root.data);
check(root.right,node);
}
}