forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidateBST.java
More file actions
43 lines (32 loc) · 857 Bytes
/
ValidateBST.java
File metadata and controls
43 lines (32 loc) · 857 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
32
33
34
35
36
37
38
39
40
41
42
43
package algoexpert.medium;
/*
PROBLEM:
Validate a BST
Solution:
1. Recursion : t: O(n) | s: O(n)
*/
public class ValidateBST {
static class BST
{
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
// t: O(n) | s: O(n)
public static boolean validator(BST tree, int min, int max)
{
if (tree == null) { return true; }
if (tree.value < min || tree.value >= max)
{ return false; }
return validator(tree.left, min, tree.value)
&& validator(tree.right, tree.value, max);
}
public static boolean validateBst(BST tree)
{
return validator(tree.left, Integer.MIN_VALUE, tree.value)
&& validator(tree.right, tree.value, Integer.MAX_VALUE);
}
}