-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIsThisABST.java
45 lines (33 loc) · 1020 Bytes
/
IsThisABST.java
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
/*
The Node class is defined as follows:
class Node {
int data;
Node left;
Node right;
}
*/
boolean checkBST(Node root) {
// If we retrieve tree as in-order and then we check if list if sorted we can find out if this is a BST
List<Integer> tree = buildTree(root);
int prev = Integer.MIN_VALUE;
for (int data: tree) {
if (data <= prev) return false;
prev = data;
}
return true;
}
// Build tree as in-order
List<Integer> buildTree(Node root) {
List<Integer> tree = new ArrayList<>();
int data = root.data;
Node left = root.left;
Node right = root.right;
if (left != null) {
tree.addAll(buildTree(left));
}
tree.add(data);
if (right != null) {
tree.addAll(buildTree(right));
}
return tree;
}