Binary search tree is a well-designed ordered set, in the case of balance, find search, insert insertion, delete deletion have O (logn) calculation time. This article discusses the specifics of implementing a binary search tree.
Each node of the binary search tree contains a key field, and up to two child nodes, and the left child is less than the current node value, and the right child is greater than the current node value. For ease of operation, each node also needs to maintain the parent node information. As can be seen from the above description, any subtree of a binary search tree is also a binary search tree.
The search operation is the basis for all operations. The search operation can be easily described by the recursive process: Key>cur.key, searching the right subtree, Key<cur.key, searching the left subtree, or Key==cur.key or encountering an empty node.
1 BOOLSt_bst::search (intVal, st_bst_node*Cur_node)2 {3 BOOLIsfind=false;4 if(cur_node==nullptr)5 {6printf"Search failed for node with value%d\n", Val);7 returnIsfind;8 }9 Ten if(cur_node->value==val) One { AIsfind=true; - } - Else if(Val < cur_node->value) the { -Isfind=search (Val, cur_node->Left ); - } - Else + { -Isfind=search (Val, cur_node->Right ); + } A at returnIsfind; -}
The insert operation finds the location that needs to be inserted, creates the node, and joins the tree.
voidSt_bst::insert (intval,st_bst_node*Cur_node) { if(Val < cur_node->value) { if(cur_node->left==nullptr) {Cur_node->left=CreateNode (Val,cur_node); } Else{Insert (val, Cur_node-Left ); } } Else if(Val > cur_node->value) { if(cur_node->right==nullptr) {Cur_node->right=CreateNode (Val,cur_node); } Else{Insert (val, Cur_node-right); } }}
The delete operation is slightly more complex than the previous two operations.
(1) If the deleted node has two children, you need to search for the node's successor node successor or the precursor node predecessor to replace the node, and then delete successor or predecessor. The successor is the smallest node in the right subtree of the node to be deleted, while the predecessor is the largest node in the left sub-tree.
(2)
Parallel binary search Tree Bianry