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>::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