-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidateBST.java
More file actions
31 lines (27 loc) · 800 Bytes
/
ValidateBST.java
File metadata and controls
31 lines (27 loc) · 800 Bytes
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
import java.util.*;
class Program {
// O(n) time | O(h) space - where n is the number of nodes in the candidate BST
// and h is the height of the BST
public static boolean validateBst(BST tree) {
// Write your code here.
return validateBST(tree, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private static boolean validateBST(BST root, int lowerBound, int upperBound) {
if (root == null) {
return true;
}
int value = root.value;
if (value < lowerBound || value >= upperBound) {
return false;
}
return validateBST(root.left, lowerBound, value) && validateBST(root.right, value, upperBound);
}
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
}