-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathProblem_05.java
51 lines (46 loc) · 1.11 KB
/
Problem_05.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
46
47
48
49
50
51
/**
* Cracking-The-Coding-Interview
* Problem_05.java
*/
package com.deepak.ctci.Ch04_Trees_And_Graphs;
import com.deepak.ctci.Library.TreeNode;
/**
* <br> Problem Statement :
*
* Implement a function to check if a binary tree is BST
*
* </br>
*
* @author Deepak
*/
public class Problem_05 {
/**
* Method to check if a binary tree is BST
*
* @param root
* @return {@link boolean}
*/
public static boolean isBST(TreeNode<Integer> root) {
return validateBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
/**
* Method to validate a binary search tree
*
* @param root
* @param min
* @param max
* @return {@link boolean}
*/
private static boolean validateBST(TreeNode<Integer> root, Integer min, Integer max) {
/* BST can have just one node */
if (root == null) {
return true;
}
/* If root's value is less then min or greater then equal to max, return false */
if (root.data < min || root.data >= max) {
return false;
}
/* Validate left and right sub trees recursively */
return validateBST(root.left, min, root.data) && validateBST(root.right, root.data, max);
}
}