forked from anthonynsimon/java-ds-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCheckBst.java
More file actions
45 lines (34 loc) · 1.26 KB
/
CheckBst.java
File metadata and controls
45 lines (34 loc) · 1.26 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
package com.anthonynsimon.algorithms.trees;
import com.anthonynsimon.datastructures.BinarySearchTree;
import com.anthonynsimon.datastructures.util.BinaryNode;
public final class CheckBst<T extends Comparable<T>> {
// Returns if the provided tree fulfills the BST property
public boolean isBst(BinarySearchTree<T> tree) {
if (tree == null) {
return false;
}
BinaryNode<T> root = tree.getRootNode();
Result<T> result = new Result<>();
recursivelyCheck(root, result);
return result.isBst;
}
// Traverses the tree in-order, keeping track of the values and checking if they are sequential
private void recursivelyCheck(BinaryNode<T> node, Result<T> result) {
if (node == null) {
return;
}
recursivelyCheck(node.getLeft(), result);
if (result.lastValue == null || node.getData().compareTo(result.lastValue) >= 0) {
result.lastValue = node.getData();
} else {
result.isBst = false;
return;
}
recursivelyCheck(node.getRight(), result);
}
// Helper class to keep track of the tree's properties
class Result<T> {
public boolean isBst = true;
public T lastValue = null;
}
}