From b413ff59029cec5e3672fcc4ffba6be71cb940b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=99=93=E8=88=AA?= <1210603696@qq.com> Date: Sat, 18 Oct 2014 11:01:22 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E8=BF=AD=E4=BB=A3=E5=99=A8--?= =?UTF-8?q?=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TinySTL/BinarySearchTree.h | 40 ++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/TinySTL/BinarySearchTree.h b/TinySTL/BinarySearchTree.h index e1b8b2d..b0bb597 100644 --- a/TinySTL/BinarySearchTree.h +++ b/TinySTL/BinarySearchTree.h @@ -222,14 +222,14 @@ namespace TinySTL{ private: const T *ptr_; cntrPtr container_; - stack stack_;//保存从root到ptr_的父节点的路径 + stack parent_;//保存从root到ptr_的父节点的路径 std::set visited_; public: bst_iter(const T *ptr, cntrPtr container) :ptr_(ptr), container_(container){ auto temp = container_->root_; while (temp &&ptr_ && temp != ptr_ && temp->data_ != ptr_->data_){ - stack_.push(temp); + parent_.push(temp); if (temp->data_ < ptr_->data_) temp = temp->right_; else if (temp->data_ > ptr_->data_) @@ -253,18 +253,18 @@ namespace TinySTL{ };//end of bst_iter template bst_iter& bst_iter::operator ++(){ - visited_.insert(ptr_); + visited_.insert(ptr_);//设为已访问 if (ptr_->right_ != 0){ - stack_.push(ptr_); + parent_.push(ptr_); ptr_ = ptr_->right_; while (ptr_ != 0 && ptr_->left_ != 0){ - stack_.push(ptr_); + parent_.push(ptr_); ptr_ = ptr_->left_; } }else{ - if (!stack_.empty() && visited_.count(stack_.top()) == 0){ - ptr_ = stack_.top(); - stack_.pop(); + if (!parent_.empty() && visited_.count(parent_.top()) == 0){//父节点未访问 + ptr_ = parent_.top(); + parent_.pop(); }else{ ptr_ = 0; } @@ -278,6 +278,30 @@ namespace TinySTL{ return res; } template + bst_iter& bst_iter::operator --(){ + visited_.erase(ptr_);//设为未访问 + if (ptr_->left_ != 0){ + parent_.push(ptr_); + ptr_ = ptr_->left_; + while (ptr_ && ptr_->right_){ + parent_.push(ptr_); + ptr_ = ptr_->right_; + } + }else{ + if (!parent_.empty() && visited_.count(parent_.top()) == 1){//父节点已经访问了 + ptr_ = parent_.top(); + parent_.pop(); + } + } + return *this; + } + template + bst_iter bst_iter::operator --(int){ + auto res = *this; + --*this; + return res; + } + template bool operator ==(const bst_iter& it1, const bst_iter& it2){ return it1.ptr_ == it2.ptr_; }