您的位置:首页 > 其它

二叉搜索树的实现(insert、find、remove)

2017-01-18 18:02 381 查看
白书研究,beginning.......

有不懂的地方欢迎留言。。。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <map>
#include <sstream>
#include <queue>
#include <stack>
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a));
#define For(a,b) for(int i = a;i<b;i++)
#define LL long long
#define MAX_N 100010
using namespace std;
struct node
{
int val;
node *lc,*rc;
};
node *insert(node *p,int x)
{
if(p == nullptr)
{
node *q = new node;
q->val = x;
q->lc = q->rc = nullptr;
//cout<<"On the way."<<endl;
return q;
}
else
{
if(x < p->val) p->lc = insert(p->lc,x);
else p->rc = insert(p->rc,x);
return p;
}
}
bool find(node *p,int x)
{
if(p == nullptr) return false;
else if(p->val == x) return true;
else if(p->val < x) return find(p->rc,x);
else if(p->val > x) return find(p->lc,x);
}
node *remove(node *p,int x)
{
if(p == nullptr) return p;
else if(p->val > x) p->lc = remove(p->lc,x);
else if(p->val < x) p->rc = remove(p->rc,x);
else if(p->lc == nullptr)
{
node *q = p->rc;
delete p;
return q;
}
else if(p->lc->rc == nullptr)
{
node *q = p->lc;
q->rc = p->rc;
delete p;
return q;
}
else
{
node *q;
for(q = p->lc; q->rc->rc != nullptr; q = q->rc) ;
node *t = q->rc;
q->rc = t->lc;
t->lc = p->lc;
t->rc = p->rc;
delete p;
return t;
}
return p;
}
int main()
{
node *head = nullptr;
int d[10] = {10,2,11,35,6,9,24};
for(int i = 0; i<7; i++)
{
head = insert(head,d[i]);
}
bool flag = find(head,6);
if(flag) cout<<"In the binary tree."<<endl;
else cout<<"Don`t in the binary tree."<<endl;
remove(head,6);
bool flag1 = find(head,9);
if(flag1) cout<<"In the binary tree."<<endl;
else cout<<"Don`t in the binary tree."<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: