您的位置:首页 > 其它

利用包装器以及lambda表达式实现二叉查找树

2015-04-26 00:46 260 查看
#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;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐