1 //与上一次实现不同,这里使用了大量的指针引用, 2 //因此节省了一个指向父节点的指针 3 #include<iostream> 4 #include<vector> 5 #include<ctime> 6 #include<cstdlib> 7 #include<sstream> 8 using namespace std; 9 10 template<class T> 11 class BinarySearchTree 12 { 13 private: 14 struct Node 15 { 16 T data; 17 Node *left; 18 Node *right; 19 int deep; 20 Node(T val,int deep) 21 { 22 data = val; 23 deep = deep; 24 left = NULL; 25 right = NULL; 26 } 27 28 private: 29 Node() 30 { 31 } 32 }; 33 Node *root; 34 int size; 35 36 public: 37 BinarySearchTree() 38 { 39 root = NULL; 40 size = 0; 41 } 42 ~BinarySearchTree() 43 { 44 clear(root); 45 root = NULL; 46 size = 0; 47 } 48 Node*& findMin(Node *&node) const 49 { 50 if(node->left == NULL) 51 return node; 52 else 53 return findMin(node->left); 54 } 55 56 void insert(Node *&node,T val,int deep ) 57 { 58 if(size == 0) 59 { 60 root = new Node(val,0); 61 size++; 62 return; 63 } 64 if(node == NULL) 65 { 66 node = new Node(val,deep); 67 size++; 68 return; 69 } 70 if(val > node->data) 71 insert(node->right,val,node->deep+1); 72 else if(val < node->data) 73 insert(node->left,val,node->deep+1); 74 else if(val == node->data) 75 { 76 } 77 } 78 79 bool contain(Node *& node,T val) const 80 { 81 if(node == NULL) 82 return false; 83 84 if(val > node->data) 85 return contain(node->right,val); 86 else if(val < node->data) 87 return contain(node->left,val); 88 else 89 return true; 90 } 91 92 void remove(Node* &node,T val) 93 { 94 if(node == NULL) 95 { 96 cout<<"remove() error! "; 97 return; 98 } 99 if(val > node->data) 100 remove(node->right,val); 101 else if(val < node->data) 102 remove(node->left,val); 103 else if(val == node->data) 104 { 105 if(node->left == NULL && node->right == NULL) 106 { 107 delete node; 108 node = NULL; 109 size--; 110 } 111 else if(node->left == NULL && node->right != NULL) 112 { 113 Node *p = node; 114 node = node->right; 115 delete p; 116 size--; 117 } 118 else if(node->left != NULL && node->right == NULL) 119 { 120 Node *p = node; 121 node = node->left; 122 delete p; 123 size--; 124 } 125 else if(node->left != NULL && node->right != NULL) 126 { 127 Node* &p = findMin(node->right); 128 node->data = p->data; 129 Node *tmp = p; 130 p = p->right; 131 delete tmp; 132 size--; 133 } 134 } 135 } 136 void clear(Node* &node) 137 { 138 if(node->left != NULL) 139 clear(node->left); 140 if(node->right != NULL) 141 clear(node->right); 142 143 delete node; 144 node = NULL; 145 } 146 void print(Node *node) 147 { 148 if(node == NULL) 149 return; 150 cout<<node->data<< " "; 151 if(node->left != NULL) 152 print(node->left); 153 if(node->right != NULL) 154 print(node->right); 155 } 156 void insert(T val) 157 { 158 insert(root,val,0); 159 } 160 void remove(T val) 161 { 162 remove(root,val); 163 } 164 void print() 165 { 166 print(root); 167 cout<<" "; 168 } 169 }; 170 171 int main() 172 { 173 BinarySearchTree<int> tree; 174 175 srand((unsigned int)time(0)); 176 for(int i=0;i<20;i++) 177 tree.insert(rand()%100-50); 178 tree.print(); 179 return 0; 180 }