1+ 'use strict' ;
2+ class Node {
3+ constructor ( data ) {
4+ this . data = data ;
5+ this . leftNode = this . rightNode = null ;
6+ }
7+ }
8+
9+ function insertionOfk ( root , k ) {
10+ if ( root == null ) return new Node ( k ) ;
11+ if ( root . data > k )
12+ root . leftNode = insertionOfk ( root . leftNode , k ) ;
13+ else if ( root . data < k )
14+ root . rightNode = insertionOfk ( root . rightNode , k ) ;
15+ return root ;
16+ }
17+
18+ function BSTtoSmallerSum ( root , sumObj ) {
19+ if ( root == null ) return null ;
20+ BSTtoSmallerSum ( root . rightNode , sumObj ) ;
21+ sumObj . sum = sumObj . sum + root . data ;
22+ root . data = sumObj . sum ;
23+ BSTtoSmallerSum ( root . leftNode , sumObj ) ;
24+
25+ }
26+
27+ function inorderDisplay ( root , inOrderArr ) {
28+ if ( root == null ) return ;
29+ inorderDisplay ( root . leftNode , inOrderArr ) ;
30+ inOrderArr . push ( root . data ) ;
31+ inorderDisplay ( root . rightNode , inOrderArr ) ;
32+ }
33+
34+ let tree = null ;
35+ tree = insertionOfk ( tree , 4 ) ;
36+ tree = insertionOfk ( tree , 2 ) ;
37+ tree = insertionOfk ( tree , 3 ) ;
38+ tree = insertionOfk ( tree , 1 ) ;
39+ tree = insertionOfk ( tree , 6 ) ;
40+ tree = insertionOfk ( tree , 5 ) ;
41+ tree = insertionOfk ( tree , 7 ) ;
42+ // Inorder display
43+ let inOrderArr = [ ] ;
44+ inorderDisplay ( tree , inOrderArr ) ;
45+ console . log ( 'Tree Inorder - ' , inOrderArr . join ( ', ' ) ) ;
46+
47+ let sumObj = { sum : 0 } ;
48+ BSTtoSmallerSum ( tree , sumObj ) ;
49+
50+ // Inorder display
51+ inOrderArr = [ ] ;
52+ inorderDisplay ( tree , inOrderArr ) ;
53+ console . log ( 'key plus sum of all greater keys in BST Inorder - ' , inOrderArr . join ( ', ' ) ) ;
0 commit comments