Delete operations for elements in binary lookup tree

Source: Internet
Author: User

About binary search tree establishment, insertion, traversal (remember that the two-fork lookup tree in the middle sequence traversal is all the elements from large to small sorting results) and other operations, Bo Master "C small plus" write very detailed, I mainly add binary tree delete operation. Delete operation is mainly difficult in the left and right child nodes are not empty nodes of the delete operation, here you can find the node in the left node of the minimum value, that is, the right child node in the leftmost subtree. After finding and exchanging data such as the node that needs to be deleted, then delete the Kid node. The implementation code is as follows: only the right child node that needs to delete the node is traversed once.

template<classT>voidBst<t&gt::D eletepri (treenode<t> *&node, T x) {    if(node = =NULL)return; if(X > Node->data) {DELETEPRI (node-Rson, X); }    Else if(X < node->data) {DELETEPRI (node-Lson, X); }    Else    {        if(Node->lson!=null && node->rson!=NULL) {TreeNode<T> *temp = node->Rson; TreeNode<T> *pre_node=NULL; TreeNode<T> *temp_node=NULL;  while(Temp->lson! =NULL) {Pre_node=temp; Temp= temp->Lson; } node->data = temp->data; Node->freq = temp->freq; Temp_node= temp->Rson; Deletetemp; Pre_node->lson =Temp_node; return; }        Else{TreeNode<T> *temp =node; if(Node->lson = =NULL) Node= node->Rson; if(Node->rson = =NULL) Node= node->Lson; Deletetemp; }    }    return ;} Template<classT>voidBst<t>::D elete (T x) {Deletepri (root, x);}
View Code

The code does not carry out many tests, should have the bug, welcome correction.

Delete operations for elements in binary lookup tree

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.