遇见一个BST的问题,然而已经忘得差不多了,参考博文敲一遍,复习一下。。。
using namespace std;
template<class T>
class TreeNode
{
public:
TreeNode() :lson(NULL), rson(NULL), freq(1) {}
T data;
unsigned int freq;
TreeNode* lson;
TreeNode* rson;
};
template<class T>
class BST
{
private:
TreeNode<T> *root;
void insertptri(TreeNode<T>* &node, T x);
TreeNode<T>* findpri(TreeNode<T>* node, T x);
void insubtree(TreeNode<T>* node);
void Delete(T x);
void Deletepri(TreeNode<T>* &node, T x);
public:
BST() :root(NULL) {}
void insert(T x);
TreeNode<T>* find(T x);
void traversal();
};
template<class T>
void BST<T>::insertptri(TreeNode<T>* &node, T x)
{
if (node == NULL) {
node = new TreeNode<T>();
node->data = x;
return;
}
if (node->data > x)
{
insertptri(node->lson, x);
}
else if (node->data)
{
insertptri(node->rson,x);
}
else ++(node->freq);
}
template<class T>
void BST<T>::insert(T x)
{
insertptri(root, x);
}
template<class T>
TreeNode<T>* BST<T>::findpri(TreeNode<T>* node, T X)
{
if (node == NULL)
return NULL;
if (node->data > x)
{
return findpri(node->lson, x);
}
else if (node->data < x)
{
return findpri(node->rson, x);
}
else return node;
}
template<class T>
TreeNode<T>* BST<T>::find(T x)
{
return findpri(root, x);
}
template <class T>
void BST<T>::Deletepri(TreeNode<T>* &node,T x)//删除操作考虑的情况比较多,各种情况都要考虑到,而且要考虑到删除之后要仔细分析怎么保持原来的树仍然是平衡二叉树
{
if (node == NULL)
return;
if (x < node->data)
Deletepri(node->lson, x);
else if (x > node->rson, x)
Deletepri(node->rson, x);
if (node->lson && node->rson)
{
TreeNode<T>* temp = node->rson;
while (temp->rson != NULL) temp = temp->rson;
node->data = temp->data;
node->freq = temp->freq;
Deletepri(node->rson, temp->data);
}
else
{
TreeNode<T>* temp = node;
if (node->lson == NULL)
node = node->rson;
if (node->rson == NULL)
node = node->lson;
delete temp;
}
}
template<class T>
void BST<T>::Delete(T x)
{
Deletepri(root, x);
}
void BST<T>::insubtree(TreeNode<T>* node)
{
if (node == NULL) return;
insubtree(node->lson);
cout << node->data << " ";
insubtree(node->rson);
}
template<class T>
void BST<T>::traversal()
{
insubtree(root);
}