• tree


    #include <iostream>
    using namespace std;

    typedef int T;
    class bst
    {
    struct Node{
    T data;
    Node* left;
    Node* right;
    Node(const T& d):data(d),left(),right(){}
    ~Node(){cout<<"~Node"<<endl;}
    };
    Node* root;
    typedef Node* tree;
    int sz;

    void clear(tree& t){
    if(t==NULL) return;
    clear(t->left);
    clear(t->right);
    delete t;
    t=NULL;

    }
    void insert(Node* pn,tree& t){
    if(pn==NULL) return;
    if(t==NULL) t=pn;
    else
    {
    if(pn->data >= t->data)
    insert(pn,t->right);
    else
    insert(pn,t->left);
    }
    }
    void travel(tree& t){
    if(t==NULL) return;
    travel(t->left);
    cout<<t->data<<' ';
    travel(t->right);
    }

    tree& find(tree& t,const T& d){
    if(t==NULL) return t;
    if(t->data==d) return t;
    if(t->data<d) return find(t->right,d);
    return find(t->left,d);
    }
    int high(tree& t){
    if(t==NULL) return 0;
    int left=high(t->left);
    int right=high(t->right);
    return left>right?left+1:right+1;
    }
    public:
    bst():root(),sz(){}

    void clear(){
    clear(root);
    sz=0;
    }
    ~bst(){
    clear();
    sz=0;
    }
    void insert(const T& d){
    Node* pn=new Node(d);
    insert(pn,root);
    sz++;
    }
    void travel(){
    travel(root);
    cout<<endl;
    }
    //查找一个元素,返回bst::Node*&类型,如果找不到返回空
    tree& find(const T& d){
    find(root,d);
    }
    //删除一个元素
    bool remove(const T& d){
    tree& t=find(root,d);
    if(t==NULL) return false;
    insert(t->left,t->right);
    Node* p =t;
    t = t->right;
    delete p;
    sz--;
    return true;
    }
    void removeAll(const T& d){
    while(remove(d));

    }
    void update(const T& old,const T& newd){
    while(remove(old)) insert(newd);
    }
    int size(){
    return sz;
    }
    int hight()
    {
    high(root);
    }
    };

    int main()
    {
    bst t;
    t.insert(4);
    t.insert(3);
    t.insert(6);
    t.insert(9);
    cout<<t.hight()<<endl;
    t.travel();
    cout<<t.find(1)<<endl;
    t.remove(3);
    t.travel();
    t.update(4,5);
    t.insert(12);
    t.insert(34);
    t.insert(5);
    t.insert(6);
    t.insert(5);
    t.travel();
    t.removeAll(5);
    t.travel();
    cout<<t.size()<<endl;
    cout<<t.hight()<<endl;
    t.clear();

    }

  • 相关阅读:
    SqlServer数据库同步方案详解(包括跨网段)
    makefile 和shell文件相互调用
    处理百万级以上的数据处理
    makefile Template(添加多个lib)
    Linux下如何删除非空目录
    makefile Template
    g++ 编译和链接
    gcc include路径
    C++ XML解析之TinyXML篇
    利用Lucene.net搭建站内搜索(2)分词技术
  • 原文地址:https://www.cnblogs.com/xiaomaogong/p/3040071.html
Copyright © 2020-2023  润新知