Skip to content

Commit 37cceff

Browse files
committed
construct BST to Greater sum tree
1 parent f09d0d0 commit 37cceff

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
 (0)