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 BSTtoGreaterSum ( root , sumObj ) {
19+ if ( root == null ) return null ;
20+ BSTtoGreaterSum ( root . rightNode , sumObj ) ;
21+ let tempData = sumObj . sum ;
22+ sumObj . sum = sumObj . sum + root . data ;
23+ root . data = tempData ;
24+ BSTtoGreaterSum ( root . leftNode , sumObj ) ;
25+
26+ }
27+
28+ function inorderDisplay ( root , inOrderArr ) {
29+ if ( root == null ) return ;
30+ inorderDisplay ( root . leftNode , inOrderArr ) ;
31+ inOrderArr . push ( root . data ) ;
32+ inorderDisplay ( root . rightNode , inOrderArr ) ;
33+ }
34+
35+ let tree = null ;
36+ tree = insertionOfk ( tree , 4 ) ;
37+ tree = insertionOfk ( tree , 2 ) ;
38+ tree = insertionOfk ( tree , 3 ) ;
39+ tree = insertionOfk ( tree , 1 ) ;
40+ tree = insertionOfk ( tree , 6 ) ;
41+ tree = insertionOfk ( tree , 5 ) ;
42+ tree = insertionOfk ( tree , 7 ) ;
43+ // Inorder display
44+ let inOrderArr = [ ] ;
45+ inorderDisplay ( tree , inOrderArr ) ;
46+ console . log ( 'Tree Inorder - ' , inOrderArr . join ( ', ' ) ) ;
47+
48+ let sumObj = { sum : 0 } ;
49+ BSTtoGreaterSum ( tree , sumObj ) ;
50+
51+ // Inorder display
52+ inOrderArr = [ ] ;
53+ inorderDisplay ( tree , inOrderArr ) ;
54+ console . log ( 'Greater Sum Tree Inorder - ' , inOrderArr . join ( ', ' ) ) ;
0 commit comments