修改求height的算法,大幅提高效率

This commit is contained in:
邹晓航
2014-10-31 15:40:21 +08:00
parent 32800c4621
commit 9596cb28df

View File

@@ -2,6 +2,7 @@
#define _BINARY_SEARCH_TREE_H_ #define _BINARY_SEARCH_TREE_H_
#include "Allocator.h" #include "Allocator.h"
#include "Queue.h"
#include "Stack.h" #include "Stack.h"
#include "String.h" #include "String.h"
@@ -25,6 +26,8 @@ namespace TinySTL{
T data_; T data_;
node *left_; node *left_;
node *right_; node *right_;
explicit node(T d = T(), node *l = 0, node *r = 0)
:data_(d), left_(l), right_(r){}
}; };
typedef TinySTL::allocator<node> nodeAllocator; typedef TinySTL::allocator<node> nodeAllocator;
public: public:
@@ -72,7 +75,7 @@ namespace TinySTL{
nodeAllocator::deallocate(ptr); 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 erase_elem(const T& val, node *&ptr);
void insert_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_min_aux(const node *ptr);
@@ -83,13 +86,28 @@ namespace TinySTL{
void print_postorder_aux(const string& delim, std::ostream& os, const node *ptr)const; void print_postorder_aux(const string& delim, std::ostream& os, const node *ptr)const;
};//end of bst class };//end of bst class
template<class T> template<class T>
size_t binary_search_tree<T>::height_aux(const node *p)const{ size_t binary_search_tree<T>::height_aux(node *p)const{
if (p == 0) TinySTL::queue<node *> q, level;
return 0; size_t nlevel = 0;
else{ if (p != 0){
return TinySTL::max(height_aux(p->left_), height_aux(p->right_)) + 1; 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<class T> template<class T>
void binary_search_tree<T>::erase_elem(const T& val, node *&ptr){ void binary_search_tree<T>::erase_elem(const T& val, node *&ptr){
if (ptr == 0) if (ptr == 0)