二叉搜索树C++实现
1 template<typename Element> 2 class BinarySearchTree 3 { 4 public: 5 BinarySearchTree():root(NULL){} 6 BinarySearchTree(const BinarySearchTree& bst):root(NULL) 7 { 8 operator=(bst); 9 } 10 virtual ~BinarySearchTree() 11 { clear(root); } 12 13 void insert(const Element& e) 14 { insert(root, e); } 15 void remove(const Element& e) 16 { remove(root, e); } 17 bool contains(const Element& e) const 18 { return contains(root, e); } 19 const Element& findMin() const 20 { return findMin(root); } 21 const Element& findMax() const 22 { return findMax(root); } 23 bool isEmpty() const 24 { return root==NULL; } 25 void clear() 26 { clear(root); } 27 28 const BinarySearchTree& operator=(const BinarySearchTree& bst) 29 { 30 if(this!=&bst) 31 { 32 clear(); 33 root = clone(bst.root); 34 } 35 return *this; 36 } 37 38 private: 39 struct BSTNode 40 { 41 Element element; 42 BSTNode *left; 43 BSTNode *right; 44 BSTNode(const Element& e, BSTNode *lt, BSTNode *rt): 45 element(e), left(lt), right(rt){} 46 }; 47 BSTNode *root; 48 49 BSTNode* clone(BSTNode * t) 50 { 51 if(t!=NULL) 52 { 53 return new BSTNode(t->element, clone(t->left), clone(t->right)); 54 } 55 return NULL; 56 } 57 void clear(BSTNode * &t) 58 { 59 if(t!=NULL) 60 { 61 clear(t->left); 62 clear(t->right); 63 delete t; 64 } 65 t = NULL; 66 } 67 void insert(BSTNode * &t, const Element& e) 68 { 69 if(t!=NULL) 70 { 71 if(e<t->element) 72 { 73 insert(t->left, e); 74 } 75 else if(e>t->element) 76 { 77 insert(t->right, e); 78 } 79 else 80 { 81 } 82 } 83 else 84 { 85 t = new BSTNode(e, NULL, NULL); 86 } 87 } 88 void remove(BSTNode * &t, const Element& e) 89 { 90 if(t!=NULL) 91 { 92 if(e<t->element) 93 { 94 remove(t->left, e); 95 } 96 else if(e>t->element) 97 { 98 remove(t->right, e); 99 } 100 else if(t->left!=NULL&&t->right!=NULL) 101 { 102 t->element = findMin(t->right); 103 remove(t->right, t->element); 104 } 105 else 106 { 107 BSTNode *tmp = t; 108 t = t->left!=NULL?t->left:t->right; 109 delete tmp; 110 } 111 } 112 } 113 bool contains(BSTNode * t, const Element& e) const 114 { 115 if(t!=NULL) 116 { 117 if(e<t->element) 118 { 119 return contains(t->left, e); 120 } 121 else if(e>t->element) 122 { 123 return contains(t->right, e); 124 } 125 else 126 { 127 return true; 128 } 129 } 130 else 131 { 132 return false; 133 } 134 } 135 const Element& findMin(BSTNode* t) const 136 { 137 return t->left!=NULL?findMin(t->left):t->element; 138 } 139 const Element& findMax(BSTNode* t) const 140 { 141 return t->right!=NULL?findMax(t->right):t->element; 142 } 143 };
注:不支持重复元素。