binarySearchTree 簡單鏈表實現
阿新 • • 發佈:2019-02-14
//binarySearchTree
struct node{
int val;
node *lson, *rson;
}
node* insert(node *p, int x){
if(p == null){
node *q = new node;
q->val = x;
q->lson = q->rson = null;
return q;
}else{
if(x < p->val) p->lson = insert(p->lson, x);
else p->rson = insert(p->rson, x);
return p;
}
}
bool find(node *p, int x){
if(p == null) return false;
else if(x == p->val) return true;
else if(x < p->val) return find(p->lson, x);
else return find(p->rson, x);
}
node* remove(node *p, int x){
if(p == null) return null;
else if(x < p->val) p->lson = remove(p->lson, x);
else if(x > p->val) p->rson = remove(p->rson, x)
else if(p->lson == null){
node *q = p->rson;
delete p;
return q;
}else if(p->lson->rson == null){
node *q = p->lson;
q->rson = p->rson;
delete p;
return q;
}else{
node *q = p->lson;
for(; q->rson->rson != null; q = q->rson);
node *r = q->rson;
q->rson = r->lson;
r->lson = p->lson;
r->rson = p->rson;
delete p;
return r;
}
return p;
}
node *root = null;
root = insert(root, x);
find(root, x);
//set、map 使用二叉搜尋樹維護
//set使用方法
int main()
{
set<int> s;
//插入元素
s.insert(1);
s.insert(3);
s.insert(5);
//查詢元素
set<int>::iterator iter;
iter = s.find(1);
if(iter == s.end()) puts("not found");
else puts("found");
//刪除元素
s.erase(3);
//其他查詢元素方法
if(s.count(3) != 0) puts("found");
else puts("not found");
//遍歷所有元素
for(iter = s.begin(); iter != s.end(); ++iter){
printf("%d\n", *iter);
}
return 0;
}
//map使用方法
int main()
{
//int為鍵, const char*為值
map<int, const char*> m;
//插入元素
m.insert(make_pair(1, "one"));
m.insert(make_pair(10, "ten"));
m[100] = "hundred";
//查詢元素
map<int, const char*>::iterator iter;
iter = m.find(1);
puts(iter->second);
iter = m.find(2);
if(iter == m.end()) puts("not found");
else puts(iter->second);
puts(m[10]);
//刪除元素
m.erase(10);
//遍歷所有元素
for(iter = m.begin(); iter != m.end(); ++iter){
printf("%d: %s\n", iter->first, iter->second);
}
return 0;
}