1
1
package me .ramswaroop .trees ;
2
2
3
3
import me .ramswaroop .common .BinaryNode ;
4
+ import me .ramswaroop .common .BinarySearchTree ;
4
5
import me .ramswaroop .common .BinaryTree ;
5
6
6
7
import java .util .List ;
13
14
* @author: ramswaroop
14
15
* @date: 6/26/15
15
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.
16
20
*/
17
- public class CheckForBST <E extends Comparable <E >> extends BinaryTree <E > {
18
-
19
- /**
20
- * Checks whether the binary tree is a BST or not.
21
- * <p/>
22
- * Approach: Performs in-order traversal of the tree and if
23
- * the result isn't in ascending order then returns false.
24
- *
25
- * @return
26
- */
27
- public boolean isBST () {
28
- //List<BinaryNode<E>> list = new ArrayList<>();
29
- BinaryNode <E > prev = new BinaryNode <>(null );
30
- return isBST (root , prev );
31
- }
21
+ public class CheckForBST {
32
22
33
23
/**
34
24
* Traverse the tree in in-order fashion and insert all nodes
@@ -38,7 +28,7 @@ public boolean isBST() {
38
28
* @param list
39
29
* @return
40
30
*/
41
- public boolean isBST (BinaryNode <E > node , List <BinaryNode <E >> list ) {
31
+ public static < E extends Comparable < E >> boolean isBST (BinaryNode <E > node , List <BinaryNode <E >> list ) {
42
32
if (node == null ) return true ;
43
33
44
34
boolean left = isBST (node .left , list );
@@ -62,7 +52,7 @@ public boolean isBST(BinaryNode<E> node, List<BinaryNode<E>> list) {
62
52
* @param prev
63
53
* @return
64
54
*/
65
- public boolean isBST (BinaryNode <E > node , BinaryNode <E > prev ) {
55
+ public static < E extends Comparable < E >> boolean isBST (BinaryNode <E > node , BinaryNode <E > prev ) {
66
56
if (node == null ) return true ;
67
57
68
58
boolean left = isBST (node .left , prev );
@@ -79,14 +69,23 @@ public boolean isBST(BinaryNode<E> node, BinaryNode<E> prev) {
79
69
}
80
70
81
71
public static void main (String a []) {
82
- CheckForBST <Integer > bt = new CheckForBST <>();
83
- bt .put (6 );
84
- bt .put (3 );
85
- bt .put (5 );
86
- bt .put (7 );
87
- bt .put (8 );
88
- bt .put (9 );
72
+ BinarySearchTree <Integer > binarySearchTree = new BinarySearchTree <>();
73
+ binarySearchTree .put (6 );
74
+ binarySearchTree .put (3 );
75
+ binarySearchTree .put (5 );
76
+ binarySearchTree .put (7 );
77
+ binarySearchTree .put (8 );
78
+ binarySearchTree .put (9 );
79
+ out .println ("Is BST: " );
80
+ out .println (isBST (binarySearchTree .root , new BinaryNode <Integer >(null )));
81
+ BinaryTree <Integer > binaryTree = new BinaryTree <>();
82
+ binaryTree .put (6 );
83
+ binaryTree .put (3 );
84
+ binaryTree .put (5 );
85
+ binaryTree .put (7 );
86
+ binaryTree .put (8 );
87
+ binaryTree .put (9 );
89
88
out .println ("Is BST: " );
90
- out .println (bt . isBST ());
89
+ out .println (isBST (binaryTree . root , new BinaryNode < Integer >( null ) ));
91
90
}
92
91
}
0 commit comments