#include<iostream>
#include<vector>
using namespace std;
template<class type>
class BSTNode;
template<class type>
class BST1;
template<class type>
class BSTNode
{
public:
friend class BST1<type>;
BSTNode(type d=type(),BSTNode<type>* left=nullptr,BSTNode<type>* right=nullptr):data(d),leftchild(left),rightchild(right)
{ }
~BSTNode()
{}
private:
BSTNode<type>* leftchild;
BSTNode<type>* rightchild;
type data;
};
template<class type>
class BST1
{
public:
BST1() :root(nullptr)
{}
BST1(type m)
{
insert(m);
}
BST1(vector<type>uv)
{
for (int i = 0; i < uv.size(); i++)
{
insert(uv[i]);
}
}
void insert(vector<type>uv)
{
for (int i = 0; i < uv.size(); i++)
{
insert(uv[i]);
}
}
void insert(type m)
{
Insert(root, m);
}
void pop(type m)
{
pop(root, m);
}
private:
void Insert(BSTNode<type>* &t, type& m)
{
if (t == nullptr)
{
t = new BSTNode<type>;
t->data = m;
return ;
}
if (m > t->data)
Insert(t->rightchild, m);
if (m < t->data)
Insert(t->leftchild, m);
}
BSTNode<type>* find(BSTNode<type>* t, type& m)
{
while (1)
{
if (t->data == m)
{
return t;
}
if (m > t->data)
{
t = t->rightchild;
}
if (m < t->data)
{
t = t->leftchild;
}
}
}
void pop_null(BSTNode<type>*& t, BSTNode<type>*m)
{
if (t == m)
{
t = nullptr;
}
else
{
if (t != nullptr)
{
pop_null(t->leftchild,m);
pop_null(t->rightchild,m);
}
}
}
BSTNode<type>* pop(BSTNode<type>* &t, type& m)
{
BSTNode<type>* p;
BSTNode <type>*p1;
p1=find(t, m);
if (p1->leftchild != nullptr && p1->rightchild != nullptr)
{
p = p1->leftchild;
while (p->rightchild != nullptr)
{
p = p->rightchild;
}
p1->data = p->data;
pop(p, m);
}
else
{
if (p1->leftchild != nullptr)
{
p = p1->leftchild;
}
else
{
p = p1->rightchild;
}
if (p == nullptr)
{
pop_null(t, p1);
}
if(p!=nullptr)
{
p1->data = p->data;
}
pop_null(t, p);
delete p;
}
return t;
}
private:
BSTNode<type>* root;
};
int main()
{
BST1<int> x;
x.insert(2);
BST1<int> x1(4);
vector<int> b= {1, 2, 3,4,5,6,7,12,46,21,32};
x1.insert(b);
x1.pop(3);
x1.pop(2);
return 0;
}
虽然可以实现的很完美,但是我感觉存在一点问题,希望大佬们可以帮我看看,是否存在内存泄露的问题,菜鸟的我难以找到。