1414 * @author: ramswaroop 
1515 * @date: 6/26/15 
1616 * @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. 
2017 */ 
2118public  class  CheckForBST  {
2219
2320    /** 
2421     * Traverse the tree in in-order fashion and insert all nodes 
2522     * 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. 
2626     * 
2727     * @param node 
2828     * @param list 
@@ -47,6 +47,8 @@ public static <E extends Comparable<E>> boolean isBST(BinaryNode<E> node, List<B
4747    /** 
4848     * Traverse the tree in in-order fashion and keep track of prev node. 
4949     * <p/> 
50+      * Concept: Perform in-order traversal of the tree and if 
51+      * the result isn't in ascending order then returns false. 
5052     * 
5153     * @param node 
5254     * @param prev 
@@ -68,6 +70,23 @@ public static <E extends Comparable<E>> boolean isBST(BinaryNode<E> node, Binary
6870        return  left  && right ;
6971    }
7072
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+ 
7190    public  static  void  main (String  a []) {
7291        BinarySearchTree <Integer > binarySearchTree  = new  BinarySearchTree <>();
7392        binarySearchTree .put (6 );
@@ -87,5 +106,9 @@ public static void main(String a[]) {
87106        binaryTree .put (9 );
88107        out .println ("Is BST: " );
89108        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 ));
90113    }
91114}
0 commit comments