Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active July 7, 2020 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/197898621ab144f06e3807a5ce9b307a to your computer and use it in GitHub Desktop.
Save primaryobjects/197898621ab144f06e3807a5ce9b307a to your computer and use it in GitHub Desktop.
Replace BST nodes with the sum of nodes greater than the node. O(n) https://jsfiddle.net/Lr3mh8op/1/
/* Given a binary tree, replace all node values with the sum of all node values greater than or equal to its own.
Note, in a binary search tree, values to the left are less than the parent, while values to the right are greater than the parent.
*/
const sum = node => {
// Returns the sum of all values in the tree.
return !node ? 0 : node.value + sum(node.left) + sum(node.right);
};
const update = (node, total) => {
if (node) {
// Calculate the total for the left.
const leftSum = sum(node.left);
// Update the node value to be the total right tree minus its own value.
node.value = total - leftSum - node.value;
// Update the rest of the tree.
update(node.left, total);
update(node.right, node.value);
}
return node;
};
const tree1 = {
value: 3,
left: {
value: 2,
},
right: {
value: 5,
}
};
const tree2 = {
value: 3,
left: {
value: 2,
left: {
value: 1,
},
right: {
value: 3,
}
},
right: {
value: 5,
left: {
value: 4,
},
right: {
value: 10,
}
}
};
$(function() {
update(tree1, sum(tree1));
$('#output').append(JSON.stringify(tree1, null, 2));
$('#output').append('\n\n------------\n\n');
update(tree2, sum(tree2));
$('#output').append(JSON.stringify(tree2, null, 2));
});
{
"value": 5,
"left": {
"value": 8
},
"right": {
"value": 0
}
}
------------
{
"value": 19,
"left": {
"value": 25,
"left": {
"value": 27
},
"right": {
"value": 22
}
},
"right": {
"value": 10,
"left": {
"value": 15
},
"right": {
"value": 0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment