Before completing the design of the binary search tree in the Tinystl project, it was found that in order to complete the design of the sequential iterator, the key step was to complete the iterator + + operation, and when the operation was implemented, 90% of the operation of the iterator could be completed very quickly.
Let's look at the definition of node:
struct node{ typedef T VALUE_TYPE; T Data_; *Left_; *Right_; Explicit 0 0 ) :d Ata_ (d), Left_ (L), Right_ (r) {} };
In the binary tree there are:
Let's see how I implemented the + + operation.
The first is to initialize the iterator:
1template<classT>2Bst_iter<t>::bst_iter (ConstS Mptr, cntrptr container)3 :p tr_ (PTR), Container_ (container) {4 if(!ptr_)5 return;6Auto TEMP = container_->root_;7 while(Temp && temp! = ptr_ && Temp->data_! = ptr_->Data_) {8 Parent_.push (temp);9 if(Temp->data_ < ptr_->Data_) {Ten //temp to the right indicates that the parent node that Temo points to does not need to be accessed again OneVisited_.insert (temp);//Add 2015.01.14 Atemp = temp->Right_; - } - Else if(Temp->data_ > ptr_->Data_) { thetemp = temp->Left_; - } - } -}
In the process of initialization, the node pointer ptr is passed in any tree, then the parent node of the node is recorded in the downward direction from root, and I use a set Visited_ to record whether the parent node is an already visited state relative to the node, Parent_. This node is logged when the node is in the right subtree of the parent node. According to the definition of the middle sequence traversal, when you want to access the next node of any node, if the node also has a right subtree is not accessed then jumps to the smallest node of the right subtree, when the node does not have the right subtree we need to go back in the order of the parent node, not all the parent nodes need to access, This parent node needs access only when the node is in the left subtree of the parent node.
1template<classT>2bst_iter<t>& Bst_iter<t>::operator++(){3Visited_.insert (PTR_);//This node is accessed4 if(Ptr_->right_) {//This node also has the right subtree .5 //Rvisited_.insert (ptr_);6 Parent_.push (ptr_);7Ptr_ = ptr_->Right_;8 while(Ptr_ && ptr_->Left_) {9 Parent_.push (ptr_);TenPtr_ = ptr_->Left_; One } A}Else{//node No right subtree can only move to parent node path -Ptr_ =0;//Add 2015.01.14 - while(!Parent_.empty ()) { thePtr_ =parent_.top (); - Parent_.pop (); - if(Visited_.count (ptr_) = =0){//The parent node has not been accessed, at which point ptr_ points to this node - Visited_.insert (ptr_); + Break; - } +Ptr_ =0;//Set as Sentinel A}//End of while at}//End of If - return* This; -}
第4-11 the row Code processing node has right subtree case. 第12-23 the case where the row Code processing node has no right subtree to move to the parent node.
A discussion on the key design of sequential iterators in binary search tree