1+ class Node
2+ {
3+ int data ;
4+ Node left , right ;
5+
6+ public Node (int item )
7+ {
8+ data = item ;
9+ left = right = null ;
10+ }
11+ }
12+
13+ public class BinaryTree
14+ {
15+ //Root of the Binary Tree
16+ Node root ;
17+
18+ /* can give min and max value according to your code or
19+ can write a function to find min and max value of tree. */
20+
21+ /* returns true if given search tree is binary
22+ search tree (efficient version) */
23+ boolean isBST () {
24+ return isBSTUtil (root , Integer .MIN_VALUE ,
25+ Integer .MAX_VALUE );
26+ }
27+
28+ /* Returns true if the given tree is a BST and its
29+ values are >= min and <= max. */
30+ boolean isBSTUtil (Node node , int min , int max )
31+ {
32+ /* an empty tree is BST */
33+ if (node == null )
34+ return true ;
35+
36+ /* false if this node violates the min/max constraints */
37+ if (node .data < min || node .data > max )
38+ return false ;
39+
40+ /* otherwise check the subtrees recursively
41+ tightening the min/max constraints */
42+ // Allow only distinct values
43+ return (isBSTUtil (node .left , min , node .data -1 ) &&
44+ isBSTUtil (node .right , node .data +1 , max ));
45+ }
46+
47+ /* Driver program to test above functions */
48+ public static void main (String args [])
49+ {
50+ BinaryTree tree = new BinaryTree ();
51+ tree .root = new Node (4 );
52+ tree .root .left = new Node (2 );
53+ tree .root .right = new Node (5 );
54+ tree .root .left .left = new Node (1 );
55+ tree .root .left .right = new Node (3 );
56+
57+ if (tree .isBST ())
58+ System .out .println ("IS BST" );
59+ else
60+ System .out .println ("Not a BST" );
61+ }
62+ }
0 commit comments