1+ 'use strict' ;
2+ class Node {
3+ constructor ( data ) {
4+ this . data = data ;
5+ this . leftNode = this . rightNode = null ;
6+ }
7+ }
8+
9+ function insertInBST ( root , data ) {
10+ if ( root == null ) return new Node ( data ) ;
11+ else if ( root . data > data ) root . leftNode = insertInBST ( root . leftNode , data ) ;
12+ else root . rightNode = insertInBST ( root . rightNode , data ) ;
13+ return root ;
14+ }
15+
16+ function rangeElements ( root , k1 , k2 , resultArr ) {
17+ if ( root == null ) return null ;
18+ if ( root . data > k1 ) rangeElements ( root . leftNode , k1 , k2 , resultArr ) ;
19+ if ( root . data >= k1 && root . data <= k2 ) resultArr . push ( root . data ) ;
20+ if ( root . data < k2 ) rangeElements ( root . rightNode , k1 , k2 , resultArr ) ;
21+ }
22+
23+ let tree = null ;
24+ tree = insertInBST ( tree , 4 ) ;
25+ tree = insertInBST ( tree , 2 ) ;
26+ tree = insertInBST ( tree , 3 ) ;
27+ tree = insertInBST ( tree , 1 ) ;
28+ tree = insertInBST ( tree , 6 ) ;
29+ tree = insertInBST ( tree , 5 ) ;
30+ tree = insertInBST ( tree , 7 ) ;
31+ // BST
32+ // 4
33+ // / \
34+ // 2 6
35+ // / \ / \
36+ // 1 3 5 7
37+ let k1 = 1 , k2 = 6 ;
38+ let resultArr = [ ] ;
39+ rangeElements ( tree , k1 , k2 , resultArr ) ;
40+ console . log ( 'Elements between ' + k1 + ' And ' + k2 + ' are - ' + resultArr . join ( ', ' ) ) ;
0 commit comments