From 9596cb28df5088d1700cf9c75d708b1469d44041 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=99=93=E8=88=AA?= <1210603696@qq.com> Date: Fri, 31 Oct 2014 15:40:21 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B1=82height=E7=9A=84?= =?UTF-8?q?=E7=AE=97=E6=B3=95=EF=BC=8C=E5=A4=A7=E5=B9=85=E6=8F=90=E9=AB=98?= =?UTF-8?q?=E6=95=88=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TinySTL/BinarySearchTree.h | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/TinySTL/BinarySearchTree.h b/TinySTL/BinarySearchTree.h index 85e5641..debd66e 100644 --- a/TinySTL/BinarySearchTree.h +++ b/TinySTL/BinarySearchTree.h @@ -2,6 +2,7 @@ #define _BINARY_SEARCH_TREE_H_ #include "Allocator.h" +#include "Queue.h" #include "Stack.h" #include "String.h" @@ -25,6 +26,8 @@ namespace TinySTL{ T data_; node *left_; node *right_; + explicit node(T d = T(), node *l = 0, node *r = 0) + :data_(d), left_(l), right_(r){} }; typedef TinySTL::allocator nodeAllocator; public: @@ -72,7 +75,7 @@ namespace TinySTL{ nodeAllocator::deallocate(ptr); } } - size_t height_aux(const node *p)const; + size_t height_aux(node *p)const; void erase_elem(const T& val, node *&ptr); void insert_elem(const T& val, node *&ptr); const_iterator find_min_aux(const node *ptr); @@ -83,12 +86,27 @@ namespace TinySTL{ void print_postorder_aux(const string& delim, std::ostream& os, const node *ptr)const; };//end of bst class template - size_t binary_search_tree::height_aux(const node *p)const{ - if (p == 0) - return 0; - else{ - return TinySTL::max(height_aux(p->left_), height_aux(p->right_)) + 1; + size_t binary_search_tree::height_aux(node *p)const{ + TinySTL::queue q, level; + size_t nlevel = 0; + if (p != 0){ + level.push(p); + ++nlevel; + while (!(q.empty() && level.empty())){ + if (level.empty()){ + ++nlevel; + while (!q.empty()){ + level.push(q.front()); + q.pop(); + } + } + auto temp = level.front(); + level.pop(); + if (temp->left_ != 0) q.push(temp->left_); + if (temp->right_ != 0) q.push(temp->right_); + } } + return nlevel; } template void binary_search_tree::erase_elem(const T& val, node *&ptr){