Delete a binary tree javascript
The complexity of deleting a node from a binary search tree depends on which node to delete. Deleting a node without a subnode is very simple. If a node has only one subnode, whether it is a left subnode or a right subnode, it becomes a little complicated, if a node contains two subnodes, it is the most complex.
If the node to be deleted is a leaf node, you only need to point the link from the parent node to its null.
If the node to be deleted contains only one subnode, the node that originally points to it must point to its subnode.
If the node to be deleted contains two subnodes, you can use either of the two methods to find the maximum value on the left subtree of the node to be deleted, one is to find the minimum value on the right node of the node to be deleted. We take the latter, find the minimum value, copy the value on the temporary node to the node to be deleted, and then delete the temporary node.
The delete operation code is as follows:
Function getSmallest (node) {// find the smallest node while (node. left! = Null) {node = node. left;} return node;} function remove (data) {root = removeNode (this. root, data); // convert the root node} function removeNode (node, data) {if (node = null) {return null;} if (data = node. data) {// if there is no subnode if (node. right = null & node. left = null) {return null; // directly set the node to null} // if there is no left subnode if (node. left = null) {return node. right; // direct to its right node} // if there is no right child node if (node. right = null) {return node. left;} // if there are two nodes if (node. right! = Null & node. left! = Null) {var tempNode = getSmallest (node. right); // find the smallest right node. data = tempNode. data; node. right = removeNode (node. right, tempNode. data); // search for return node;} else if (data