remove
. We'll build the logic for our deletion operation in here. First, you'll want to create a function within remove that finds the node we are trying to delete in the current tree. If the node is not present in the tree, remove
should return null
. Now, if the target node is a leaf node with no children, then the parent reference to it should be set to null
. This effectively deletes the node from the tree. To do this, you will have to keep track of the parent of the node we are trying to delete as well. It will also be useful to create a way to track the number of children the target node has, as this will determine which case our deletion falls under.
We will handle the second and third cases in the next challenges. Good luck!
BinarySearchTree
data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The BinarySearchTree
data structure exists.'');'
- text: The binary search tree has a method called remove
.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == ''function'')})(), ''The binary search tree has a method called remove
.'');'
- text: Trying to remove an element that does not exist returns null
.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; return (test.remove(100) == null); })(), ''Trying to remove an element that does not exist returns null
.'');'
- text: 'If the root node has no children, deleting it sets the root to null
.'
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(500); test.remove(500); return (test.inorder() == null); })(), ''If the root node has no children, deleting it sets the root to null
.'');'
- text: The remove
method removes leaf nodes from the tree
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(5); test.add(3); test.add(7); test.add(6); test.add(10); test.add(12); test.remove(3); test.remove(12); test.remove(10); return (test.inorder().join('''') == ''567''); })(), ''The remove
method removes leaf nodes from the tree'');'
```