二叉搜索树的三种实现 —— 指针 | set | map

一、指针实现:

///表示节点的结构体
struct node
{
    int val;
    node *lch , *rch;
};
///插入数值x
node *insert(node *p , int x)
{
    if(p == NULL)
    {
        node *q = new node;
        q -> val = x;
        q -> lch = q -> rch = NULL;
        return q;
    }
    else
    {
        if(x < p -> val)p -> lch = insert(p -> lch , x);
        else p -> rch = insert(p -> rch , x);
        return p;
    }
}
///查找数值x
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 -> lch , x);
    else return find(p -> rch , x);
}
///删除数值x
///1.需要删除的节点没有左儿子,那么就把右儿子提上去
///2.需要删除的节点的左儿子没有右儿子,那么就把他的左儿子提上去
///3.以上两种情况都不满足的话,就把左儿子的子孙中最大的节点提到需要删除的节点上
node *remove(node *p , int x)
{
    if(p == NULL)
    {
        return NULL;
    }
    else if(x < p -> val)p -> lch = remove(p -> lch , x);
    else if(x > p -> val)p -> rch = remove(p -> rch , x);
    else if(p -> lch == NULL)
    {
        node *q = p -> rch;
        delete p;
        return q;
    }
    else if(p -> lch -> rch == NULL)
    {
        node *q = p -> lch;
        q -> rch  = p -> rch;
        delete p;
        return q;
    }
    else
    {
        node *q;
        for(q = p -> lch ; q -> rch -> rch != NULL ; q = q -> rch);
        node *r = q -> rch;
        q -> rch = r -> lch;
        r -> lch = p -> lch;
        r -> rch = p -> rch;
        delete p;
        return r;
    }
    return p;
}

二、set 实现:

#include <iostream>
#include <cstdio>
#include <set>
using namespace std;
int main()
{
    set <int> s;
    s.insert(1);
    s.insert(3);
    s.insert(5);
    set <int> :: iterator ite;
    ite = s.find(1);
    if(ite == s.end())puts("not found");
    else puts("found");
    ite = s.find(2);
    if(ite == s.end())puts("not found");
    else puts("found");

    s.erase(3);

    if(s.count(3) != 0)puts("found");
    else puts("not found");

    for(ite = s.begin() ; ite != s.end() ; ite ++)
    {
        printf("%d\n" , *ite);
    }
    return 0;
}

三、map实现:

#include <iostream>
#include <cstdio>
#include <map>
#include <string>
using namespace std;
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 ite;
    ite = m.find(1);
    puts(ite->second);
    ite = m.find(2);
    if(ite == m.end())puts("no found");
    else puts(ite->second);

    puts(m[10]);///其他写法
    ///删除元素
    m.erase(10);
    for(ite = m.begin() ; ite != m.end() ; ++ite)
    {
        printf("%d: %s\n" , ite->first , ite->second);
    }
    return 0;
}


你可能感兴趣的:(ACM,二叉搜索树)