Last active
January 5, 2020 18:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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