@@ -21,8 +21,8 @@ public class CheckForBST {
21
21
* Traverse the tree in in-order fashion and insert all nodes
22
22
* in a list and check for sort order of list.
23
23
* <p/>
24
- * Concept: Perform in -order traversal of the tree and if
25
- * the result isn't in ascending order then returns false .
24
+ * Concept: In -order traversal of a BST is always sorted in ascending
25
+ * manner .
26
26
*
27
27
* @param node
28
28
* @param list
@@ -45,10 +45,12 @@ public static <E extends Comparable<E>> boolean isBST(BinaryNode<E> node, List<B
45
45
}
46
46
47
47
/**
48
- * Traverse the tree in in-order fashion and keep track of prev node.
48
+ * Traverse the tree in in-order fashion and keep track of its in-order
49
+ * predecessor value. If at any point current node's value is found greater
50
+ * than its predecessor value then return {@code false}.
49
51
* <p/>
50
- * Concept: Perform in -order traversal of the tree and if
51
- * the result isn't in ascending order then returns false .
52
+ * Concept: In -order traversal of a BST is always sorted in ascending
53
+ * manner .
52
54
*
53
55
* @param node
54
56
* @param prev
@@ -71,6 +73,12 @@ public static <E extends Comparable<E>> boolean isBST(BinaryNode<E> node, Binary
71
73
}
72
74
73
75
/**
76
+ * Simplest way to test whether a binary tree is a BST or not.
77
+ * <p/>
78
+ * CONCEPT: A node's left sub-tree cannot have a value more than
79
+ * the node's value and similarly the node's right sub-tree cannot
80
+ * have a value less than the node's value.
81
+ *
74
82
* @param node
75
83
* @param minValue
76
84
* @param maxValue
@@ -88,6 +96,7 @@ public static <E extends Comparable<E>> boolean isBST(BinaryNode<E> node, E minV
88
96
}
89
97
90
98
public static void main (String a []) {
99
+ // in-order approach
91
100
BinarySearchTree <Integer > binarySearchTree = new BinarySearchTree <>();
92
101
binarySearchTree .put (6 );
93
102
binarySearchTree .put (3 );
@@ -106,6 +115,7 @@ public static void main(String a[]) {
106
115
binaryTree .put (9 );
107
116
out .println ("Is BST: " );
108
117
out .println (isBST (binaryTree .root , new BinaryNode <Integer >(null )));
118
+ // min max approach
109
119
out .println ("Is BST: " );
110
120
out .println (isBST (binarySearchTree .root , Integer .MIN_VALUE , Integer .MAX_VALUE ));
111
121
out .println ("Is BST: " );
0 commit comments