Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cb25886

Browse files
committed
BST greater with sum key
1 parent a4eac98 commit cb25886

File tree

1 file changed

+53
-0
lines changed

1 file changed

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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /