1
+ /* Uses Inorder traversal. Only works on unique element BT */
2
+ public class BinarySearchTreeCheck {
3
+ Node root ;
4
+
5
+ public BinarySearchTreeCheck () {
6
+ root = null ;
7
+ }
8
+
9
+ public class Node {
10
+ int value ;
11
+ Node left ;
12
+ Node right ;
13
+
14
+ public Node (int value ) {
15
+ this .value = value ;
16
+ this .left = null ;
17
+ this .right = null ;
18
+ }
19
+
20
+ public void setLeft (Node left ) {
21
+ this .left = left ;
22
+ }
23
+
24
+ public Node getLeft () {
25
+ return left ;
26
+ }
27
+
28
+ public void setRight (Node right ) {
29
+ this .right = right ;
30
+ }
31
+
32
+ public Node getRight () {
33
+ return right ;
34
+ }
35
+
36
+ public int getValue () {
37
+ return value ;
38
+ }
39
+ }
40
+
41
+ public void createBinaryTree (int option ) {
42
+ root = new Node (10 );
43
+ Node one = new Node (8 );
44
+ Node two = new Node (5 );
45
+ Node three = new Node (9 );
46
+ Node four = new Node (15 );
47
+ switch (option ) {
48
+ case 1 : /* Is BST (Only unique elements) */
49
+ root .setLeft (one );
50
+ root .setRight (four );
51
+ one .setLeft (two );
52
+ one .setRight (three );
53
+ break ;
54
+ case 2 : /* Not BST (Only unique elements) */
55
+ root .setRight (two );
56
+ root .setLeft (one );
57
+ one .setLeft (four );
58
+ one .setRight (three );
59
+ break ;
60
+ default :
61
+ break ;
62
+ }
63
+ }
64
+
65
+ public boolean isBSTBetter () {
66
+ if (root == null )
67
+ return true ;
68
+ return isBSTBetter (root );
69
+ }
70
+
71
+ private Integer prev = null ;
72
+
73
+ public boolean isBSTBetter (Node cur ) {
74
+ if (cur == null )
75
+ return true ;
76
+
77
+ // Check for the left subtree
78
+ if (!isBSTBetter (cur .getLeft ())) {
79
+ return false ;
80
+ }
81
+
82
+ // Check the cur value and update prev
83
+ if (prev != null && cur .getValue () <= prev )
84
+ return false ;
85
+ prev = cur .getValue ();
86
+
87
+ // Check for the right subtree
88
+ if (!isBSTBetter (cur .getRight ())) {
89
+ return false ;
90
+ }
91
+
92
+ return true ;
93
+ }
94
+
95
+ public static void main (String [] args ) {
96
+ BinarySearchTreeCheck btOne = new BinarySearchTreeCheck ();
97
+ btOne .createBinaryTree (1 );
98
+ BinarySearchTreeCheck btTwo = new BinarySearchTreeCheck ();
99
+ btTwo .createBinaryTree (2 );
100
+
101
+ // Only works if all the elements in the Binary Tree are unique.
102
+ System .out .println (btOne .isBSTBetter ());
103
+ System .out .println (btTwo .isBSTBetter ());
104
+ }
105
+ }
0 commit comments