Skip to content

Instantly share code, notes, and snippets.

@cozzbie
Last active January 5, 2020 18:40
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 cozzbie/ee7d14e446de879a38585901e712adfd to your computer and use it in GitHub Desktop.
Save cozzbie/ee7d14e446de879a38585901e712adfd to your computer and use it in GitHub Desktop.
Given a binary tree, delete a node from it by making sure that tree shrinks from the bottom.
const rightMost = tree => {
if(!tree.right){
return tree;
}
return rightMost(tree.right);
}
const deleteRmt = tree => {
if(!tree){
return;
}
if(tree.right.data === undefined){
delete tree.right;
return;
}
return deleteRmt(tree.right);
}
const deleteNode = (tree, key) => {
const rmt = rightMost(tree);
const axe = [tree];
while(axe.length){
const chosen = axe.shift();
if(chosen.data == key){
chosen.data = rmt.data;
rmt.data = undefined;
deleteRmt(tree);
break;
}else{
chosen.left && axe.push(chosen.left);
chosen.right && axe.push(chosen.right)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment