binarySearchTree 简单链表实现

来源:互联网 发布:长沙大火知乎 编辑:程序博客网 时间:2024/06/05 19:46
//binarySearchTreestruct 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;}