From 303a07d6ace17ea24d19f919008fc95720311c19 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 12:22:59 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E5=99=A8=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=96=B0=E6=8E=A5=E5=8F=A3=EF=BC=8Cbst=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E6=9B=B4=E5=B9=B3=E8=A1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TinySTL/BinarySearchTree.h | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/TinySTL/BinarySearchTree.h b/TinySTL/BinarySearchTree.h index b0bb597..d650f31 100644 --- a/TinySTL/BinarySearchTree.h +++ b/TinySTL/BinarySearchTree.h @@ -48,6 +48,7 @@ namespace TinySTL{ bool empty()const{ return root_ == 0; } size_t size()const{ return size_; } + const_iterator root(){ return const_iterator(root_, this); } const_iterator cbegin(){ return find_min(); } const_iterator cend(){ return const_iterator(0, this); } @@ -87,9 +88,12 @@ namespace TinySTL{ return 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_); + size_t choose = size_ % 2; + //随机选择删除左右,使得删除操作更平衡 + auto pos = (choose == 0? + const_cast(find_min_aux(ptr->right_).ptr_) : const_cast(find_max_aux(ptr->left_).ptr_)); ptr->data_ = pos->data_; - return erase_elem(pos->data_, ptr->right_); + return (choose == 0 ? erase_elem(pos->data_, ptr->right_) : erase_elem(pos->data_, ptr->left_)); }else{ //has one or no child auto temp = ptr; if (ptr->left_ == 0) @@ -241,6 +245,9 @@ namespace TinySTL{ const_reference operator*(){ return ptr_->data_; } const_pointer operator ->(){ return &(operator*()); } + bst_iter left()const{ return bst_iter(ptr_->left_, container_); } + bst_iter right()const{ return bst_iter(ptr_->right_, container_); } + bst_iter& operator ++(); bst_iter operator ++(int); bst_iter& operator --();