Binary search tree creation && Find & Insert & Delete

Source: Internet
Author: User

Binary Search Tree deletion:

You will need to find this node from the tree before you delete it, and then determine how to delete it for the situation.

There are three cases, the first is that this node has no children node, this node has a child node, this node has two child nodes

void Delete (bintree*& root,int value) {bintree* delnode= null;if (root = NULL) return; bintree* temp = root; bintree* parent =null;while (temp!=null) {if (Temp->value = = value) break;else{parent = temp;if (Temp->value > Value) temp = Temp->left;elsetemp =temp->right; }}if (temp ==null) return;d Elnode = temp;//The deleted node is found based on the condition of the node being deleted//If the node does not have children then delete this node directly if (Delnode->right ==null &amp ;& delnode->left ==null) {cout<< "= = =" <<endl;//cout<<parent->value<<endl;if ( Delnode = = root) {root=null;} if (parent && parent->left = = Delnode) {parent->left = NULL;} if (parent && parent->right = = delnode) parent->right =null;delete Delnode;} If this node has a child if (delnode->right! = NULL && delnode->left==null) {if (parent!=null) {if (Parent->left = = Delnode) Parent->left = Delnode->right;else if (parent->right = = delnode) Parent->right = delnode->right;} Else{root = Delnode->right;} Delete Delnode;} if (Delnode->left!)=null&&delnode->right== NULL) {if (parent!=null) {if (Parent->left = = delnode) Parent->left = delnode- >left;else if (parent->right = delnode) parent->right = delnode->right;} Else{root = Delnode->left;} Delete Delnode;} Two nodes are not empty if (delnode->left!=null && delnode->right!=null) {temp = Delnode->right;parent = Delnode; while (Temp->left!=null) {parent = Temp;temp = Temp->left;} Delnode->value = Temp->value;parent->left = Temp->right;delete Temp;//delete (delnode->right,temp- >value);  } }


Binary search tree creation && Find & Insert & Delete

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.