#include<iostream>
#include<functional>
using namespace std;
template <class T>
class tree
{
private:
struct Node
{
T data;
Node* L;
Node* R;
Node(T d) :data(d), L(NULL), R(NULL){}
};
Node* root;
int Count;
public:
tree() :root(NULL), Count(0){}
tree& Insert(T d)
{
function<tree&(Node*&, T&)> ins = [&](Node*& r, T& dd)->tree&
{
if (r == NULL)
{
r = new Node(dd);
return *this;
}
else if (dd < r->data)
{
return ins(r->L, dd);
}
else
{
return ins(r->R, dd);
}
};
Count++;
return ins(root, d);
}
void Travel()
{
function<void(Node*&)> tra = [&](Node*& r)
{
if (r == NULL)
{
return;
}
tra(r->L);
cout << r->data << " ";
tra(r->R);
};
tra(root);
}
Node*& Find(T d)
{
function<Node*&(Node*&, T)> fid = [&](Node*& r, T dd)->Node*&
{
if (r == NULL)
{
return r;
}
else if (r->data == dd)
{
return r;
}
else if (r->data < dd)
{
return fid(r->R, dd);
}
else
{
return fid(r->L, dd);
}
};
return fid(root, d);
}
bool If_empty()
{
return root == NULL;
}
bool Remove(T d)
{
function<bool(Node*, T)> rem = [&](Node* r, T dd)
{
Node*& temp = Find(dd);
if (temp == NULL)
{
return false;
}
Node* p = temp;
if (temp->L)
{
//無論有沒有右子樹,都不用考慮
Node* pn = temp->R;
while (pn->L)
{
pn = pn->L;
}
pn->L = temp->L;
}
temp = temp->R;
delete p;
p = NULL;
return true;
};
return rem(root, d);
}
void updata(T d)
{
Insert(d);
}
void clear()
{
function<void(Node*&)> cls = [&](Node*& r)
{
if (r == NULL)
{
return;
}
cls(r->L);
cls(r->R);
delete r;
r = NULL;
};
cls(root);
}
int high()
{
function<int(Node*)> h = [&](Node* r)
{
if (r == NULL)
{
return 0;
}
int lh = h(r->L);
int rh = h(r->R);
return 1 + (lh > rh ? lh : rh);
};
return h(root);
}
};
int main()
{
tree<int> t;
t.Insert(5);
t.Insert(2);
t.Insert(1);
t.Insert(3);
t.Insert(6);
t.Insert(4);
t.Travel();
cout << endl;
t.Remove(2);
t.Travel();
cin.get();
return 0;
}