Data Structure Learning series Binary search tree

Source: Internet
Author: User

Binary search tree (BST) is an important application of the two-fork tree, it adds a property on the basis of a binary tree: For each node in the tree, if there is a left son, the value of its left son must be less than its own value, and if there is a right son, the value of its right son must be greater than its own value.

Binary search tree operations generally have insert, delete and find , the average time complexity of these operations are O (LOGN), insert and find operations is simple, the deletion is a bit more complicated, in addition, because the binary tree in the middle sequence traversal is an ordered sequence, I added a middle order traversal operation.

Binary tree has three kinds of traversal modes: pre-sequence Traversal (pre-order), Middle sequence traversal (in-order), post-ordertraversal (post-order). Keep in mind that the so-called "before and after " means that the current node is processed before, between, and after two sub-nodes .

Binary Search Tree defects

If key insertion is similar to a random model, the simple implementation of the binary lookup tree provides fast search and Insert, as well as rank,Select,Delete, and range lookups. But in reality,worst-case is not impossible to happen, such as the client inserting key in full order or in reverse . The performance of the algorithm degrades to N and becomes a linear lookup, so this possibility is why we are looking for better algorithms and data structures.

Binary search Tree application is not many, because it is the worst time with the linear table, most of it will be applied to its upgraded version, balanced binary tree and red black tree, both trees can be the time complexity of the stability of O (Logn) around. Although not used, but binary search tree is a must to learn, after all, it is a balance between the binary tree and the foundation of the red and black trees.

Next step, write a binary search tree.

From the tree to start the introduction:

    • Introduction to the Tree

1. Definition of a tree

A tree is a data structure that consists of N (n>=1) of finite nodes that form a hierarchical set of relationships.

It's called a "tree" because it looks like an upside down tree, which means it's rooted up and leaves facing down. It has the following characteristics:
(01) Each node has 0 or more sub-nodes;
(02) A node without a parent node is called the root node;
(03) Each non-root node has and only one parent node;
(04) In addition to the root node, each child node can be divided into multiple disjoint subtrees.

2. Basic terminology of trees

If a node has a subtree, then the node is called the "parent" of subtree, and the root of the subtree is the "child" of the node. The nodes with the same parents are "brothers" to each other. Any node on all subtrees of a node is descended from that node. All nodes on the path from the root node to a node are ancestors of that node.

node degree : The number of subtrees owned by the node.
Leaf : A zero-degree junction.
Branch node : A node with a non-zero degree.
The degree of the tree : The maximum degree of the node in the tree.

hierarchy : The root node level is 1, the rest of the nodes are equal to the level of the parent node of the node plus 1.
height of the tree : The maximum level of nodes in the tree.
unordered tree : You can swap locations if the order of the sub-trees in the tree is unimportant.
ordered Tree : If the order of the sub-trees in the tree is important, the position cannot be exchanged.
Forest : consists of 0 or more disjoint trees. By adding a root to the forest, the forest becomes a tree; by deleting the root, the tree becomes the forest.

    • Introduction of Binary Tree

1. Definition of two-fork tree

A binary tree is a tree structure with a maximum of two subtrees per node. It has five basic forms: the two-fork tree can be an empty set, the root can have a left or right subtree, or the left and right subtrees are empty.

    • Introduction to Binary search tree

Binary search tree, also known as binary tree. combines the flexibility of two-point lookup with the efficient and linked list structure.
It is a special two-fork tree: For binary trees, suppose X is a node in a two-fork tree, X-nodes contain the keyword key, and the key value of Node x is recorded as Key[x]. If Y is a node in the left subtree of x, then key[y] <= key[x], and if Y is a node of the right subtree of x, then key[y] >= key[x]. So this tree is a binary search tree. As shown in the following:

In the binary lookup tree:
(01) If the left subtree of any node is not empty, the value of all nodes on the left subtree is less than the value of its root node;
(02) The right subtree of any node is not empty, then the value of all nodes on the right subtree is greater than the value of its root node;
(03) The left and right sub-trees of any node are also two-fork search trees respectively.
(04) No nodes with key values equal (no duplicate nodes).

    • Insert

Depending on the nature of the binary search tree, when inserting a node, if the root node is empty, this node as the root node, if the root node is not empty, it is necessary to compare with the root node, if the value is smaller than the root node, inserted into the left subtree of the root node, if the value is larger than the root node is inserted into the right subtree of the root node, so recursively Locate the inserted location. The insertion of a repeating node is marked with a freq in the value range. 2 is a process of inserting.

Insert sequence: 6 7 2 1 3 4

: The insertion process of a sequence

The time complexity of binary search tree depends on the shape of this tree, if it is closer to one by one complete binary tree, then the time complexity is around O (logn), if you encounter 3 such a two fork tree, then the time complexity will revert to the linear O (n).

A balanced binary tree will be a good solution to 3 of this situation.

//Inserttemplate<classT>voidBst<t>::insertpri (treenode<t>* &node,t x) {    if(Node==null)//If the node is empty, the X information is added at this node{node=NewTreenode<t>(); Node->data=x; return; }    if(node->data>x)//if x is less than the value of the node, it continues to insert X in the left subtree of the node{INSERTPRI (node-lson,x); }    Else if(node->data<x)//if x is greater than the value of the node, it continues to insert X in the right subtree of the node{INSERTPRI (node-rson,x); }    Else+ + (node->freq);//if it's equal, add 1 to the frequency.}//Insert Interfacetemplate<classT>voidBst<t>:: Insert (T x) {insertpri (root,x);}
View Code
    • Find

The function of finding is almost the same as inserting, recursive in the same way as inserting, returning the address of the node if found, and returning null if not found.

The Find and insert process for binary lookup trees is very similar, because the insertion process is actually a lookup, and then the insertion is performed at the point where the lookup stops when it cannot be found.

//Findtemplate<classT>TreeNode<t>* Bst<t>::findpri (treenode<t>*node,t x) {    if(Node==null)//If the node is empty, the description is not found and returns null    {        returnNULL; }    if(node->data>x)//if x is less than the value of the node, it continues to find X in the left subtree of the node    {        returnFindpri (node->lson,x); }    Else if(node->data<x)//if x is greater than the value of the node, continue looking for x in the left subtree of the node    {        returnFindpri (node->rson,x); }    Else returnNode//If they are equal, this node is found}//Find Interfacestemplate<classT>TreeNode<t>* bst<t>:: Find (T x) {returnFindpri (root,x);}
View Code
    • Delete

For trees, deletion is the most complex, with two main considerations.

<1> Single Child Situation

This is relatively simple, if the deletion of the node has left the child that left the child on the top, if there is a right child to the right child on top, and then finish the call.

<2> There are children around the situation.

The first thing you can imagine is that if we were to delete an element of an array, then we'd delete one of the elements behind it to the deleted position.

So the two-tree operation is also the same, we find the next node to delete the node according to the "Middle sequence traversal", and then top up on the line, the principle is the same as "array".

Also here is a note, in the add operation, we append the value of the repeating element to the "additional domain", then when the deletion, we can first determine the

Not to "1" operation rather than the actual deletion of nodes, in fact, this is "lazy delete", very interesting.

If the number of deletions is not many, there is a way to delete the faster, the name is lazy Delete method: When an element is to be deleted, it remains in the tree, just a deletion of a tag. The advantage of this approach is that removing the time overhead of that step avoids the time overhead of allocating space if you reinsert the deleted node. The disadvantage is that the depth of the tree increases, the time complexity of the lookup increases, and the insertion time may increase.

//Deletetemplate<classT>voidBst<t>::D eletepri (treenode<t>* &node,t x) {    if(Node==null)return;//a node with a value of x not found    if(X < node->data) DELETEPRI (Node-&GT;LSON,X);//if x is less than the value of the node, it continues to delete the X in the left subtree of the node    Else if(X > Node->data) DELETEPRI (Node-&GT;RSON,X);//if x is greater than the value of the node, it continues to delete the X in the right subtree of the node    Else//if equal, this node is the node to be deleted    {        if(Node->lson&&node->rson)//There are two sons of this node{TreeNode<t>* temp=node->rson;//temp pointing to the right son of the node             while(temp->lson!=null) temp=temp->lson;//Find the node with the lowest value in the right sub-tree//assigns the value of the smallest node in the right subtree to this nodeNode->data=temp->data; Node->freq=temp->freq; DELETEPRI (Node->rson,temp->data);//Delete the node with the smallest value in the right subtree        }        Else//there are 1 or 0 sons of this node{TreeNode<t>* temp=node; if(Node->lson==null)//with a right son or no son .Node=node->Rson; Else if(Node->rson==null)//have left sonNode=node->Lson; Delete(temp); }    }    return;}//Remove Interfacetemplate<classT>voidBst<t>::D elete (T x) {deletepri (root,x);}
View Code
    • Traverse

Iterates through all nodes of the tree and accesses it only once. According to the location of the root node is divided into the pre-sequence traversal, the middle sequence traversal, post-order traversal.

Pre-sequence traversal: The right subtree, left dial hand tree, root node

Middle Sequence traversal: the right subtree, the root node, left dial hand tree

Post-post traversal: root node, right subtree, left dial hand tree

For example: Three traversal of the tree below is asked

Pre-sequence traversal: ABDEFGC

Middle Sequence Traversal: DEBGFAC

Post-post traversal: EDGFBCA

 /*   previous sequence traversal as an example using recursive method to implement * pre-order Traversal "binary tree"  */ template  < Class  T>void  bstree<t>::p reorder (bstnode<t>* tree) const  { if  ( Tree!= << tree->key << "   ;        Preorder (tree ->left);    Preorder (tree ->right); }}template  <class  t>void  Bstree<t>::p Reorder () {preorder (mroot);}  

Reference Links:

Http://www.cnblogs.com/skywang12345/p/3576328.html

Http://www.cnblogs.com/skywang12345/p/3576373.html

Http://www.cnblogs.com/huangxincheng/archive/2012/07/21/2602375.html

Http://www.cppblog.com/cxiaojia/archive/2016/02/27/186752.html

Http://www.cppblog.com/cxiaojia/archive/2011/11/16/rumen.html

Data Structure Learning series Binary search 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.