14
14
* @author: ramswaroop
15
15
* @date: 6/26/15
16
16
* @time: 7:14 PM
17
- *
18
- * Concept: Perform in-order traversal of the tree and if
19
- * the result isn't in ascending order then returns false.
20
17
*/
21
18
public class CheckForBST {
22
19
23
20
/**
24
21
* Traverse the tree in in-order fashion and insert all nodes
25
22
* in a list and check for sort order of list.
23
+ * <p/>
24
+ * Concept: Perform in-order traversal of the tree and if
25
+ * the result isn't in ascending order then returns false.
26
26
*
27
27
* @param node
28
28
* @param list
@@ -47,6 +47,8 @@ public static <E extends Comparable<E>> boolean isBST(BinaryNode<E> node, List<B
47
47
/**
48
48
* Traverse the tree in in-order fashion and keep track of prev node.
49
49
* <p/>
50
+ * Concept: Perform in-order traversal of the tree and if
51
+ * the result isn't in ascending order then returns false.
50
52
*
51
53
* @param node
52
54
* @param prev
@@ -68,6 +70,23 @@ public static <E extends Comparable<E>> boolean isBST(BinaryNode<E> node, Binary
68
70
return left && right ;
69
71
}
70
72
73
+ /**
74
+ * @param node
75
+ * @param minValue
76
+ * @param maxValue
77
+ * @param <E>
78
+ * @return
79
+ */
80
+ public static <E extends Comparable <E >> boolean isBST (BinaryNode <E > node , E minValue , E maxValue ) {
81
+ if (node == null ) return true ;
82
+
83
+ if (node .value .compareTo (minValue ) < 0 || node .value .compareTo (maxValue ) > 0 ) {
84
+ return false ;
85
+ }
86
+
87
+ return isBST (node .left , minValue , node .value ) && isBST (node .right , node .value , maxValue );
88
+ }
89
+
71
90
public static void main (String a []) {
72
91
BinarySearchTree <Integer > binarySearchTree = new BinarySearchTree <>();
73
92
binarySearchTree .put (6 );
@@ -87,5 +106,9 @@ public static void main(String a[]) {
87
106
binaryTree .put (9 );
88
107
out .println ("Is BST: " );
89
108
out .println (isBST (binaryTree .root , new BinaryNode <Integer >(null )));
109
+ out .println ("Is BST: " );
110
+ out .println (isBST (binarySearchTree .root , Integer .MIN_VALUE , Integer .MAX_VALUE ));
111
+ out .println ("Is BST: " );
112
+ out .println (isBST (binaryTree .root , Integer .MIN_VALUE , Integer .MAX_VALUE ));
90
113
}
91
114
}
0 commit comments