From b9ec71a5192b28c613410f37cb3373fc5f15ef17 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 09:04:31 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90bst=E7=9A=84=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E5=85=83=E7=B4=A0=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TinySTL/BinarySearchTree.h | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/TinySTL/BinarySearchTree.h b/TinySTL/BinarySearchTree.h index dbca645..abc9784 100644 --- a/TinySTL/BinarySearchTree.h +++ b/TinySTL/BinarySearchTree.h @@ -40,6 +40,7 @@ namespace TinySTL{ void insert(const T& val); template void insert(Iterator first, Iterator last); + void erase(const T& val); bool empty()const{ return root_ == 0; } @@ -58,6 +59,7 @@ namespace TinySTL{ nodeAllocator::deallocate(ptr); } } + void erase_elem(const T& val, node *&ptr); void insert_elem(const T& val, node *&ptr); const_iterator find_min_aux(const node *ptr); const_iterator find_max_aux(const node *ptr); @@ -67,6 +69,33 @@ namespace TinySTL{ void print_postorder_aux(const string& delim, std::ostream& os, const node *ptr)const; };//end of bst class template + void binary_search_tree::erase_elem(const T& val, node *&ptr){ + if (ptr == 0) + return; + if (ptr->data_ != val){ + if (val < ptr->data_) + erase_elem(val, ptr->left_); + else + erase_elem(val, ptr->right_); + }else{ // found + if (ptr->left_ != 0 && ptr->right_ != 0){// has two children + auto pos = const_cast(find_min_aux(ptr->right_).ptr_); + ptr->data_ = pos->data_; + erase_elem(pos->data_, ptr->right_); + }else{ //has one or no child + nodeAllocator::deallocate(ptr); + if (ptr->left_ == 0) + ptr = ptr->right_; + else + ptr = ptr->left_; + } + } + } + template + void binary_search_tree::erase(const T& val){ + erase_elem(val, root_); + } + template void binary_search_tree::insert_elem(const T& val, node *&ptr){//重复的元素不插入 if (ptr == 0){ ptr = nodeAllocator::allocate(); @@ -171,6 +200,9 @@ namespace TinySTL{ //class of bst iterator template//T = node class bst_iter{ + private: + template + friend class binary_search_tree; private: typedef typename binary_search_tree::vaule_type value_type; typedef typename binary_search_tree::const_reference const_reference; @@ -183,7 +215,20 @@ namespace TinySTL{ operator const T*(){ return ptr_; } const_reference operator*(){ return ptr_->data_; } const_pointer operator ->(){ return &(operator*()); } + public: + template + friend bool operator ==(const bst_iter& it1, const bst_iter& it2); + template + friend bool operator !=(const bst_iter& it1, const bst_iter& it2); }; + template + bool operator ==(const bst_iter& it1, const bst_iter& it2){ + return it1.ptr_ == it2.ptr_; + } + template + bool operator !=(const bst_iter& it1, const bst_iter& it2){ + return !(it1 == it2); + } } }