@@ -56,35 +56,40 @@ class BinarySearchTree {
5656
5757 /**
5858 * Remove a node from the tree
59- * @param { any } value value to remove from the tree
59+ * @returns { boolean } false if not found and true if it was deleted
6060 */
6161 remove ( value ) {
62- let current = this . root ;
63- let parent = this . root ;
62+ const found = this . find ( value ) ;
63+ if ( ! found ) return false ;
6464
65- // search for the parent of the element
66- while ( current ) {
67- if ( current . value === value ) {
68- if ( parent . left . value === value ) {
69- // value is on the left side
70- parent . left = current . right || current . left ;
71- if ( current . left ) {
72- parent . left . left = current . left ;
73- }
74- } else {
75- // value is on the right side
76- parent . right = current . right || current . left ;
77- if ( current . left ) {
78- parent . right . left = current . left ;
79- }
80- }
65+ const { parent } = found ;
8166
82- return true ;
67+ if ( found === this . root ) {
68+ this . root = found . right || found . left ; // replace root
69+ // if the root had any left subtree, place it at the end of the new root subtree.
70+ if ( found . left ) {
71+ const newRootLeftmost = this . getMin ( this . root . left ) ;
72+ newRootLeftmost . left = found . left ;
8373 }
84- parent = current ;
85- current = value >= current . value ? current . right : current . left ;
74+
75+ return true ;
8676 }
87- return false ;
77+
78+ if ( parent . left === found ) {
79+ parent . left = found . right || found . left ;
80+
81+ if ( found . left ) {
82+ parent . left . left = found . left ;
83+ }
84+ } else if ( parent . right === found ) {
85+ parent . right = found . right || found . left ;
86+
87+ if ( found . left ) {
88+ parent . right . left = found . left ;
89+ }
90+ }
91+
92+ return true ;
8893 }
8994
9095 /**
@@ -203,7 +208,7 @@ class BinarySearchTree {
203208 }
204209
205210 /**
206- * Get the node with the max value of subtree: the righ -most value.
211+ * Get the node with the max value of subtree: the right -most value.
207212 * @param {TreeNode } root subtree's root
208213 */
209214 getMax ( root = this . root ) {
@@ -215,7 +220,7 @@ class BinarySearchTree {
215220 }
216221
217222 /**
218- * Get the node with the min value of subtree: the let -most value.
223+ * Get the node with the min value of subtree: the left -most value.
219224 * @param {TreeNode } root subtree's root
220225 */
221226 getMin ( root = this . root ) {
0 commit comments