Delete a binary tree javascript

Source: Internet
Author: User

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
 
  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.