C + + implementation of binary search tree

Source: Internet
Author: User

Binary lookup tree (binary search Tree,bst), (also: two fork search tree, binary sort tree) it is either an empty tree or a two-tree with the following properties: If its left subtree is not empty, then the value of all nodes on the left subtree is less than the value of its root node; if its right subtree is not empty, The value of all nodes on the right subtree is greater than the value of its root node, and its left and right subtrees are also two-fork sort trees.

The sequential traversal binary sorting tree can get an ordered sequence of a keyword, an unordered sequence can be constructed by constructing a binary sort tree into an ordered sequence, and the process of constructing the tree is the process of ordering the unordered sequence (in fact, the process of building BST is the process of fast sorting the data, that is, the fast algorithm). Therefore, it is usually possible to sort the data by constructing a binary lookup tree, whose time complexity is O (NLOGN), the search for BST, the time complexity of insertion and deletion is the height of the tree, O (LOGN).

Let's take a look at the operations that this article implements for BST.

void Create_tree (node **tree,int data),//Generate two fork lookup tree void mid_travel (node *tree);//sequence Traversal tree node* find_node (node *tree,int data );//Find node* Find_parent_node (node *tree,int data);//Find the parent node of the data node node* insert_node (node **tree,int data);//Insert Data node* GET_MIN_PARENT_PTR (node *tree);//The Father pointer node* get_max_patent_ptr (node *tree) that obtains the minimum value of the tree;//Gets the tree's maximum father pointer bool Delete_ node **tree,int data;//delete the specified node

Where node is defined as:

typedef struct TREE_NODE {    int data;//data field    struct Tree_node *r_child;//left child node    struct Tree_node *l_child;// Right child node}node;

Then look at the generation of BST Create_tree (), where the first parameter is a level two pointer to the root node of BST, note that this must be passed in as a level two pointer, and then failed to construct, and the second parameter is the data used to generate BST.

1/* 2  * Generate two fork Tree 3  * Tree: Level two pointer, point to Spanning Tree 4  * Data: Spanning Tree's stats 5  * Note: This can only be passed to level two pointer 6  * author:rio_2607 7 */  8 VO ID create_tree (node **tree,int data) 9 {Ten     if (NULL = = *tree) One     {         *tree = (node *) malloc (sizeof (node)); 13< c9/> (*tree)->data = data;14         (*tree)->l_child = null;15         (*tree)->r_child = null;16         return;17     }18     Else if (Data < (*tree)->data)//If the data of the root node is small, insert the left subtree of the Roots node         create_tree (& (*tree)->l _child), data), or     if (Data > (*tree)->data)//If it is greater than the root node's data, insert the right subtree into the root node         create_tree (& ((*tree ->r_child), data),     else23     {         cout << "duplicate data" << endl;25         return;26     }27}

Then look at the BST to find, it is very simple, first take the data to be looked up with the root node data comparison, if the small root node data, then recursive to the root node of the left sub-tree to find, if larger than the root node of the data, then the right subtree recursive search, if the search for large leaf node has not been found, The data you are looking for does not exist and the code is as follows:

1/* 2  * Find if data exists 3  * If present, returns a pointer to the corresponding node otherwise returns NULL 4  * author:rio_2607 5 *  /6 node* Find_node (node *tree, int Data) 8 {9     if (data = = Tree->data)         return tree;11     else if (data < Tree->data && Tree->l_ Child! = NULL)         //If data is small on the root node, the Zuozi is searched for         return Find_node (tree->l_child,data);     > Tree->data && tree->r_child! = NULL)         If data is larger than the root node, look for the right subtree and return to the         Find_node ( Tree->r_child,data); +     return null;18}

Take a look at the Insert node:

1/* 2  * Insert data in the appropriate position 3  * Tree: Two level pointer, point to binary search tree 4  * data: To be inserted 5  * Returns the pointer of the inserted node 6  * author:rio_2607 7 *  / 8 node* Insert_node (node **tree,int data) 9 {Ten     node *temp = (node *) malloc (sizeof (node));     temp->data = data;     temp->l_child = null;13     temp->r_child = null;14     if (NULL = = *tree)//If *tree is empty, the tree has no data, Then directly insert the     {         *tree = temp;18         return *tree;19     }20     else if (Data < (*tree)->data)// If the data of the root node is small, it is inserted into his record          return Insert_node (& ((*tree)->l_child), data), and all     else if (Data > (*tree) ->data)//If data is larger than the root node, insert into the right subtree to          Insert_node (& (*tree)->r_child), data);     {         cout << "Cannot add duplicate data" << endl;27         return null;28     }29}

In fact, for BST, generate, find, insert is a very simple recursive operation, the trouble is to delete the node. So how do you delete the BST node?

Due to the particularity of BST, BST has the following four distinct properties:

1, the minimum value of the right subtree of BST, no Zuozi (if any, it will not be the minimum value, because it's all the values on the left subtree are small values of the root node)

2, the maximum value of the left subtree of BST, there is no right subtree (if any, it will not be the maximum value, because all of its right subtree values are greater than the value of the root node)

3. The maximum value in the left subtree of BST must be located on the rightmost node in the left subtree

4. The minimum value of the right subtree in BST must be located on the leftmost node in the right subtree

How do you understand these four words? As shown in the following:

Take the following node as an example, the minimum value of the right subtree of the root node is 15,15, which is located at the leftmost end of the right subtree, has no left subtree, the maximum value of Zuozi is 12, is located at the far right of Zuozi, and there is no right subtree.

Ok, understand the above points, you can delete the node operation. The operation to delete a node is:

1. Locate the node you want to delete p

2, first look at the node P No there is a right subtree, if there is a right subtree, find the minimum value in the right subtree, assign this minimum value to the node to be deleted, and then delete this found minimum node, delete some of the finishing work

3, if the node P does not have the right subtree, then find the maximum value of the left subtree of the node p, assign the maximum value to the node to be deleted, and then delete the maximum node, some finishing work

4, if the node P has neither the left subtree nor the right sub-tree, the node p is a leaf node, directly deleted can be deleted when some finishing work

For example, if you want to delete node 13, then first find the right subtree of node 13, the minimum value, here is the node 15, after finding the node 15, the data of this node, that is, 15 is assigned to the node to be deleted 13, and then the node 15 parent node, here is 19, The left child pointer points to the right child node of node 15, here is node 17, and then delete node 15, you can. As shown in the following:

Because this is used to the minimum node of the right subtree, recorded as M, also to use the minimum node of the parent node, recorded as p, so we directly find the minimum node of the parent node, here is the node 19, using the following code to operate:

1//Assume that the node to be deleted is the D2//min node's parent node is p, the minimum node is m3//where m = p->l_child4 D->data = M->data5 P->l_child = M->r_child6 Free (m)

When looking for the parent node of the minimum value of the right subtree, a special situation is encountered, such as:

To remove the node 1, first to find the right subtree node 1 of the minimum node, is node 2, but in this right subtree, Node 2 does not have a parent node (because this is the right subtree of Node 1, node 1 is not included in the right subtree), at this point, the minimum node's parent node is the minimum node itself, in this case, The L_child node of parent node p is empty. So in the code, to special deal with this situation: directly assign the parent node P's data field to the node to be deleted, and then the node to be deleted (here is node 1) The right child pointer to the parent node (here is Node 2) the right child node (here is node 5), and then delete node 2.

For example, suppose we want to delete node 13, because node 13 does not have a right subtree, so we want to find the node 13 of the Zuozi (here by node 10, node 12 and node 11) The maximum value, here is node 12, after finding, the maximum node (node 12) of the data assigned to the node to be deleted, Here is node 13, and then the right child pointer of the parent node of the maximum direct point (here is node 10) points to the left child node of the maximum node (here is node 11), and then deletes the maximum direct point (node 12). As shown in:

Similarly, when dealing with this situation, as in the above, there will be a special situation, as shown in:

To remove node 14, find the maximum value of his left subtree for node 10, but in this Zuozi (not including node 14), node 10 has no parent node, or node 10 's parent node is himself, this situation should be handled separately, the same way as above.

This is quite simple if the node to be deleted is a leaf node, but it is important to note that the pointer field (L_child or r_child) of the parent node of the leaf node is set to null after the leaf node has been deleted. See the code for specific operation.

OK, now it's ready for the code. The first is get_min_parent_ptr ()

1/* 2  * Returns the pointer to the parent of the minimum node in the tree 3  * Minimum value must be a leaf node in Zuozi 4  * author:rio_2607 5 *  /6 node* get_min_parent_ptr (node *t REE) 7 {8     if (NULL = = tree) 9     {         cout << "tree is empty" << endl;11         return null;12     }13
   //This situation corresponds to the case where the parent node is recorded as itself,     if (tree->l_child = = NULL)         return tree;16,     node *tree_temp = tree;18     node *temp = tree_temp->l_child;19 while     (temp->l_child! = NULL) #     {         tree_temp = temp;22< C18/>temp = temp->l_child;23     }24     return tree_temp;26 27}

Next is Get_max_patent_ptr ()

1/* 2  * Returns a pointer to the parent node of the maximum node in the tree 3  * The maximum value must be the leaf node in the right subtree 4  * author:rio_2607 5 *  /6 node* get_max_patent_ptr (node *t REE) 7 {8     if (NULL = = tree) 9     {         cout << "tree is empty" << endl;11         return null;12     }13
   //This situation corresponds to the case where the parent node is recorded as itself,     if (tree->r_child = = NULL)         return tree;16,     node *tree_temp = tree;18     node *temp = tree_temp->r_child;19 while     (temp->r_child! = NULL) #     {         tree_temp = temp;22< C17/>temp = temp->r_child;23     }24     return tree_temp;26}

Next is Get_parent_ptr ()

1/* 2  * Locate the parent node of the specified node 3  * Returns a pointer to the parent node, otherwise returns null 4  * Generally only finds the parent node of the leaf node 5  * author:rio_2607 6 */  7 node* Find_par Ent_node (node *tree,int data) 8 {9     if (data = = Tree->data)         return tree;11     if (Data < Tree->data &am p;& tree->l_child! = NULL)     {         if (data = = Tree->l_child->data)             return tree;15         Else16             return Find_parent_node (tree->l_child,data);     }18     else if (Data > Tree->data & & Tree->r_child! = NULL) +     {         if (data = = Tree->r_child->data)             return tree;22         Else23             return Find_parent_node (tree->r_child,data);     }25     return null;26}

Next is the specific code to delete the node Delete_node ():

 1/* 2 * Delete Data node 3 * author:rio_2607 4 */5 bool Delete_node (node **tree,int value) 6 {7 Node *value_ptr = Find_ Node (*tree,value);         8 if (NULL = = value_ptr) 9 {cout << value << ' not ' in the data << endl;11 return false;12}13 14//If the data to be deleted is a leaf node, find the parent node of the leaf node, clear the child node pointer of the parent node, and then delete the leaf node, if (NULL = = Value_ptr->l_child && NULL = = value_ptr->r_child) 16 {17//leaf node must have parent node, find parent node *parent_ptr = Find_parent_no De (*tree,value); 19//Determine if the leaf node is the left node of the parent node and the right node (parent_ptr->l_child->data = = value) Pare Nt_ptr->l_child = Null;22 else if (parent_ptr->r_child->data = = value) Parent_ptr->r_chil D = null;24 free (value_ptr); 25//Note that the corresponding pointer field for the parent node of the root node is emptied to true;27}28//If value_pt R's right subtree exists, then find the minimum value of the right subtree, if (value_ptr->r_child! = NULL)-{to Node *min_parent_ptr = Get_min_parent_ptr (val Ue_ptR->r_child); if (min_parent_ptr! = NULL && Min_parent_ptr->l_child! = null) 33 {34 Node *delete_ptr = min_parent_ptr->l_child;//of the minimum value of the right subtree Value_ptr->data = delete_ptr->data;// The value of the data field of the node to be removed is assigned the minimum value of the right subtree 36//The left subtree of the parent node of the node with the minimum value points to the right subtree of the minimum node 37//Because the minimum node does not have a left subtree of min_parent_pt         R->l_child = delete_ptr->r_child;39 free (delete_ptr);//delete min node-return true;41}42 else if (min_parent_ptr! = null && NULL = = Min_parent_ptr->l_child) 43 {44//if MIN_PA Rent_ptr->l_child is empty, indicating that the tree with value_ptr as the root node has no left subtree 45//The root node of the right subtree of value_ptr is the minimum value of Value_ptr->data = min_parent_ptr->data;47 value_ptr->r_child = min_parent_ptr->r_child;48 Free (min_parent_p TR); return true;50}51}52//If there is no left dial hand tree in the right subtree, find the maximum value of the left subtree, or else if (NULL = = Value_ptr->r_c Hild && value_ptR->l_child! = NULL) *max_parent_ptr = Get_max_patent_ptr (value_ptr->l_child); X_parent_ptr! = NULL && Max_parent_ptr->r_child! = null) $ {$ node *delete_ptr = Max_paren             t_ptr->r_child;//Zuozi Max node pointer value_ptr->data = delete_ptr->data;//the data field to delete the node is assigned the maximum value of Zuozi 60 Assigns the right subtree of the parent node of the maximum node to the left subtree of the maximum node 61//Because the maximum node has no right subtree Max_parent_ptr->r_child = delete_ptr->l_ch ild;63 free (delete_ptr); true;65 return}66 else if (max_parent_ptr! = NULL &             & null = = Max_parent_ptr->r_child) 67 {68//If Max_parent_ptr->r_child is empty, description value_ptr no right subtree 69 The root node of the left subtree of value_ptr is the maximum value of Value_ptr->data = max_parent_ptr->data;71 VALUE_PTR-&G T;l_child = max_parent_ptr->l_child;72 free (max_parent_ptr); return true;74}75} False;7 return8} 

Two fork Lookup tree for C + + implementation

Related Article

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.