Introduction to algorithms --------- Binary Search Tree

Source: Internet
Author: User

Introduction to algorithms --------- Binary Search Tree

First, the code for deleting the binary tree search tree, because deletion is the most complex operation of the binary tree search:

Int BinarySearchTree
 
  
: Tree_remove (const T & elem) {BinarySearchTreeNode
  
   
* Z = tree_search (elem); // locate the node to be deleted based on the element. BinarySearchTreeNode
   
    
* X, * y; if (z! = NULL) {// use y to indicate the actual node to be deleted if (z-> left = NULL | z-> right = NULL) // there is only one son node at most, or no son node y = z; elsey = tree_search (tree_successor (elem )); // when there are two sons, the successor node is actually deleted. // because of the preceding if statement, y has only one son or no son. The successor node only has the right son or no son. // Therefore, x is either a son node or an empty node if (y-> left! = NULL) x = y-> left; elsex = y-> right; if (x! = NULL) // determines whether the y node has a son node. Some Flowers will convert the parent node of the y node to the parent node of x. X-> parent = y-> parent; // if (y-> parent = NULL) root = x when y is the root node or not the root node; else if (y = y-> parent-> left) // What if node y is not the root node? Y-> parent-> left = x; elsey-> parent-> right = x; // process the successor node, because y indicates y in the successor node! = Z; if (y! = Z) z-> elem = y-> elem; delete y;} return-1 ;}
   
  
 


The concept and operation of the Binary Search Tree. The main content includes the nature of the Binary Search Tree, how to find the maximum, minimum, and given values in the binary search tree, and how to find the precursor and successor of an element, how to insert and delete data in the binary search tree. The time for performing these basic operations on the binary search tree is proportional to the height of the tree. The expected height of a random binary search tree is O (lgn ), therefore, the average operation time of the basic dynamic set is θ (lgn ).

1. Binary Search Tree

The binary search tree is organized according to the binary tree structure. Therefore, it can be represented by the binary linked list structure. The storage method of the keywords in the binary search tree satisfies the following characteristics: set x to a node in the binary search tree. If y is a node in the left subtree of x, key [y] is less than or equal to key [x]. If y is a node in the right subtree of x, key [x] is less than or equal to key [y]. According to the features of the binary search tree, we can use the middle root to traverse a binary search tree, and we can get a sequence of small to large keywords in the tree.

The search result of a binary tree and its root traversal is shown in:

The book provides a theorem: If x is the root of a subtree Containing n knots, the root traversal Runtime is θ (n ).

Q: What is the difference between the Binary Search Tree and the minimum heap? Can I use the minimum heap property to output all the keywords in the Tree Containing n nodes in order within the O (n) Time?

2. query the Binary Search Tree <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + CqGhoaG2/examples/NfWo6yz/cHLu/examples + examples/W1rLp0a + 9 + NDQwcvP6s + examples/examples + bXEudi8/examples + examples + bXE1/examples/a1vb/examples/bPMo7qjqLLp1dK5/bPMw7 + 0ztTa1/PT0tfTyvfW0Nf2s/examples/o6k8L3A + examples = "http://www.2cto.com/uploadfile/Collfiles/20141204/20141204090119189.png" alt = "\">

The book provides recursive and non-recursive pseudocode for the search process:

TREE_SEARCH (x, k) if x = NULL or k = key [x] then return x if (k
 
  
ITERATIVE_TREE_SEARCH (x, k) while x! = NULL and k! = Key [x] do if k
   
    

(2) Search for the maximum and minimum keywords

Based on the characteristics of the binary tree, it is easy to find the largest and smallest keywords. Search for the smallest keyword in a binary tree: Start from the root node and follow the left pointer of each node until the end of NULL. If a node x has no left subtree, the minimum keyword in the subtree with x as the root is key [x]. Search for the maximum keyword in a binary tree: Start from the root node and follow the right pointer of each node until the end of NULL. The book provides the pseudocode for finding the maximum and minimum keywords:

 TREE_MINMUM(x)while left[x] != NULL do x=left[x]return x

TREE_MAXMUM(x)while right[x] != NULLdo x= right[x]return x


(3) precursor and successor

Given a node in the binary search tree, find the node's forward and next in the central order traversal order. If all the keywords in the fruit tree are different, the precursor of a node x is the largest node among all the keywords smaller than the key [x, the successor is the node that is greater than the smallest of all the keywords in key [x. Based on the structure and nature of the binary search tree, you can find the precursor and successor of a node without comparing the keywords.

Search precursor step: first determine whether x has a left subtree. If yes, search for the node with the largest keyword in left [x], that is, the precursor of x. If there is no left subtree, execute this operation from x until a node is the right child node of its parent node. For example, the process of finding the precursor node 6 of node 7:

Follow-up steps: first determine whether x has the right subtree. If yes, find the node with the smallest keyword in right [x], even if x is followed. If there is no right subtree, search up from the parent node of x until a node is the end point of the Left son of its parent node. For example, the process of finding the successor node 15 of node 13:

The book provides the pseudocode for finding the successor node of the x node:

TREE_PROCESSOR(x)    if right[x] != NULL        then return TREE_MINMUM(right(x))    y=parent[x]    while y!= NULL and x ==right[y]           do x = y               y=parent[y]    return y


Theorem: For a binary SEARCH with h height, the running time of SEARCH, MINMUM, MAXMUM, SUCCESSOR, and PROCESSOR operations in a dynamic set is O (h ).

3. insert and delete

Insertion and deletion may change the dynamic set represented by binary search. It is difficult to maintain the nature of the binary search tree during insertion and deletion. The Insert Process is relatively simple, and it is complicated to delete nodes.

(1) Insert

The location of the inserted node corresponds to the node location when the search fails. Therefore, you need to start from the root node to find the location of the inserted node, and then insert it. As shown in the insert node process:

The book provides the pseudocode for the Insert Process:

TREE_INSERT(T,z)    y = NULL;    x =root[T]    while x != NULL        do y =x            if key[z] < key[x]                 then x=left[x]                 else  x=right[x]     parent[z] =y     if y=NULL        then root[T] =z        else if key[z]>key[y]                   then  keft[y]  = z                   else   right[y] =z


The runtime of the insert process is O (h), and h is the height of the tree.

(2) Delete

Delete the given node z from the Binary Search Tree in three cases:

<1> If node z does not have left and right subtree, modify its parent node p [z] to make it NULL. Shows the deletion process:

<2> If node z has only one subtree (left or right subtree), create a chain between the child and the parent node to delete z. Shows the deletion process:

<3> If z has two children, delete z's successor y (y has no left child) and replace z's content with y.

The book provides the pseudocode for the deletion process:

TREE_DELETE(T,z)    if left[z] ==NULL or right[z] == NULL       then y=z       else  y=TREE_SUCCESSOR(z)   if left[y] != NULL       then x=left[y]       else  x=right[y]   if x!= NULL       then parent[x] = parent[y]   if p[y] ==NULL      then root[T] =x      else if y = left[[prarnt[y]]                  then left[parent[y]] = x                  else  right[parent[y]] =x    if y!=z        then key[z] = key[y]              copy y's data into z     return y

Theorem: For a binary search tree with h in height, the running time of INSERT and DELETE operations in a dynamic set is O (h ).

4. Implement Testing

The C ++ language is used to implement a simple binary search tree and supports basic operations on dynamic sets: search, minmum, maxmum, predecessor, successor, insert, and delete. The binary search tree structure is as follows:

template
     
      class BinarySearchTreeNode{public:T elem;BinarySearchTreeNode
      
        *parent;BinarySearchTreeNode
       
         *left;BinarySearchTreeNode
        
          *right;};template
         
          class BinarySearchTree{public:BinarySearchTree();void tree_insert(const T& elem);int tree_remove(const T& elem);BinarySearchTreeNode
          
            *tree_search(const T& elem) const;T tree_minmum(BinarySearchTreeNode
           
            * root) const;T tree_maxmum(BinarySearchTreeNode
            
             * root) const;T tree_successor(const T& elem) const;T tree_predecessor(const T& elem) const;int empty() const;void inorder_tree_walk() const;BinarySearchTreeNode
             
              * get_root() { return root; }private:BinarySearchTreeNode
              
               * root;};
              
             
            
           
          
         
        
       
      
     


The complete procedure is as follows:

# Include
     
      
# Include
      
       
Using namespace std;/* buckets * // * uses the C ++ language to implement a simple binary search tree, supporting the basic operations of dynamic sets: * // * search, minmum, maxmum, predecessor, successor, insert, and delete. The binary search tree structure is as follows: * // * processed */template
       
        
Class BinarySearchTreeNode {public: T elem; BinarySearchTreeNode
        
         
* Parent; BinarySearchTreeNode
         
          
* Left; BinarySearchTreeNode
          
            * Right;}; template
           
             Class BinarySearchTree {public: BinarySearchTree (); void tree_insert (const T & elem); int tree_remove (const T & elem); BinarySearchTreeNode
            
              * Tree_search (const T & elem) const; T tree_minmum (BinarySearchTreeNode
             
               * Root) const; T tree_maxmum (BinarySearchTreeNode
              
                * Root) const; T tree_successor (const T & elem) const; T tree_predecessor (const T & elem) const; int empty () const; void inorder_tree_walk () const;
               
                 * Get_root () {return root;} private: BinarySearchTreeNode
                
                  * Root;}; // constructor, which initializes the binary search tree. Template
                 
                   BinarySearchTree
                  
                    : BinarySearchTree () {root = NULL;} template
                   
                     Void BinarySearchTree
                    
                      : Tree_insert (const T & elem) {if (! Empty () {BinarySearchTreeNode
                     
                       * P_node = root; BinarySearchTreeNode
                      
                        * Q_node = NULL; BinarySearchTreeNode
                       
                         * New_node = new BinarySearchTreeNode
                        
                          ; New_node-> elem = elem; new_node-> left = NULL; new_node-> right = NULL; new_node-> parent = NULL; while (p_node) {q_node = p_node; if (p_node-> elem) p_node = p_node-> left; elsep_node = p_node-> right;} // when p_node is empty, q_node is the parent node with the correct insertion position, and q_node is the leaf node. if (q_node-> elem) q_node-> left = new_node; elseq_node-> right = new_node; new_node-> parent = q_node;} else {root = new BinarySearchTreeNode
                         
                           ; Root-> elem = elem; root-> parent = NULL; root-> left = NULL; root-> right = NULL ;}// Delete template of the Binary Search Tree node
                          
                            Int BinarySearchTree
                           
                             : Tree_remove (const T & elem) {BinarySearchTreeNode
                            
                              * Z = tree_search (elem); BinarySearchTreeNode
                             
                               * X, * y; if (z! = NULL) {// use y to indicate the actual node to be deleted if (z-> left = NULL | z-> right = NULL) // there is only one son node at most, or no son node y = z; elsey = tree_search (tree_successor (elem )); // when there are two sons, the successor node is actually deleted. // because of the preceding if statement, y has only one son or no son. The successor node only has the right son or no son. // Therefore, x is either a son node or an empty node if (y-> left! = NULL) x = y-> left; elsex = y-> right; if (x! = NULL) x-> parent = y-> parent; if (y-> parent = NULL) root = x; else if (y = y-> parent-> left) y-> parent-> left = x; elsey-> parent-> right = x; // process the successor node, because y indicates that the successor node is y! = Z; if (y! = Z) z-> elem = y-> elem; delete y;} return-1;} // BinarySearchTreeNode
                              
                                * Return type. Return the node template of the elem search element.
                               
                                 BinarySearchTreeNode
                                
                                  * BinarySearchTree
                                 
                                   : Tree_search (const T & elem) const {BinarySearchTreeNode
                                  
                                    * Pnode = root; while (pnode) {if (pnode-> elem = elem) break; else if (pnode-> elem) pnode = pnode-> left; elsepnode = pnode-> right;} return pnode;} // elements that return the minimum keyword. You can use the recursive method to write a template in the reference books.
                                   
                                     T BinarySearchTree
                                    
                                      : Tree_minmum (BinarySearchTreeNode
                                     
                                       * Root) const {BinarySearchTreeNode
                                      
                                        * Pnode = root; while (pnode-> left) pnode = pnode-> left; return pnode-> elem;} // elements that return the maximum keyword. You can use recursion instead, however, the efficiency of the template is reduced.
                                       
                                         T BinarySearchTree
                                        
                                          : Tree_maxmum (BinarySearchTreeNode
                                         
                                           * Root) const {BinarySearchTreeNode
                                          
                                            * Pnode = root; while (pnode-> right! = NULL) pnode = pnode-> right; return pnode-> elem;} // subsequent node template
                                           
                                             T BinarySearchTree
                                            
                                              : Tree_successor (const T & elem) const {BinarySearchTreeNode
                                             
                                               * Pnode = tree_search (elem); BinarySearchTreeNode
                                              
                                                * Parentnode; if (pnode! = NULL) {if (pnode-> right) return tree_minmum (pnode-> right); parentnode = pnode-> parent; while (parentnode & pnode = parentnode-> right) {pnode = parentnode; parentnode = parentnode-> parent;} if (parentnode) return parentnode-> elem; elsereturn T ();} return T () ;}// template of the frontend Node
                                               
                                                 T BinarySearchTree
                                                
                                                  : Tree_predecessor (const T & elem) const {BinarySearchTreeNode
                                                 
                                                   * Pnode = tree_search (elem); BinarySearchTreeNode
                                                  
                                                    * Parentnode; if (pnode! = NULL) {if (pnode-> right) return tree_maxmum (pnode-> right); parentnode = pnode-> parent; while (parentnode & pnode = parentnode-> left) {pnode = parentnode; parentnode = pnode-> parent;} if (parentnode) return parentnode-> elem; elsereturn T ();} return T ();} template
                                                   
                                                     Int BinarySearchTree
                                                    
                                                      : Empty () const {return (NULL = root);} // output the Binary Search Tree in order of size, that is, the result of root traversal is the binary search tree. use the stack function. Template
                                                     
                                                       Void BinarySearchTree
                                                      
                                                        : Inorder_tree_walk () const {if (NULL! = Root) {stack
                                                       
                                                         *> S; BinarySearchTreeNode
                                                        
                                                          * P_temp; P_temp = root; while (NULL! = P_temp |! S. empty () {if (NULL! = P_temp) {s. push (P_temp); P_temp = P_temp-> left;} else {P_temp = s. top (); s. pop (); cout <P_temp-> elem <""; P_temp = P_temp-> right ;}}} int main () {BinarySearchTree
                                                         
                                                           Bstree; BinarySearchTreeNode
                                                          
                                                            * Ptnode, * proot; bstree. tree_insert (32); bstree. tree_insert (21); bstree. tree_insert (46); bstree. tree_insert (54); bstree. tree_insert (16); bstree. tree_insert (38); bstree. tree_insert (70); cout <"inorder tree walk is:"; bstree. inorder_tree_walk (); proot = bstree. get_root (); cout <"\ nmax value is:" <bstree. tree_maxmum (proot) <endl; cout <"min value is:" <bstree. tree_minmum (proot) <endl; ptnode = bstree. tree_search (38); if (ptnode) cout <"the element 38 is exist in the binary tree. \ n "; elsecout <" the element 38 is not exist in the binary tree. \ n "; cout <" the successor of 38 is: "<bstree. tree_successor (38) <endl; cout <"the predecessor of 38 is:" <bstree. tree_predecessor (38) <endl; if (bstree. tree_remove (46) = 0) cout <"delete 46 successfully" <endl; elsecout <"delete 46 failed" <endl; cout <"inorder tree walk is:"; bstree. inorder_tree_walk (); exit (0 );}
                                                          
                                                         
                                                        
                                                       
                                                      
                                                     
                                                    
                                                   
                                                  
                                                 
                                                
                                               
                                              
                                             
                                            
                                           
                                          
                                         
                                        
                                       
                                      
                                     
                                    
                                   
                                  
                                 
                                
                               
                              
                             
                            
                           
                          
                         
                        
                       
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     

The program test results are as follows:



The running time of various basic operations on the binary search is O (h), and h is the height of the tree. However, the height of the tree changes during element insertion and deletion. If n elements are inserted in a strictly increasing order, the height of the constructed binary search tree is n-1. For example, Elements 7, 15, 18, 20, 34, 46, and 59 are inserted sequentially to construct a binary search tree. The binary search tree structure is as follows:

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.