zoukankan      html  css  js  c++  java
  • 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();

    }

  • 相关阅读:
    Vmware Tools的安装与共享文件夹
    2.4 运行JSOP
    2.3 接口fit
    查看与修改主机名
    2.2 接口usr
    vue-router 在微信浏览器中操作history URl未改变的解决方案
    vue使用axios发送请求,都会发送两次请求
    axios对请求各种异常情况处理的封装
    axios设置请求头内容
    vue中的axios.post使用json数据传输,出现请求头字段内容类型是不被允许的情况的解决方案
  • 原文地址:https://www.cnblogs.com/xiaomaogong/p/3040071.html
Copyright © 2011-2022 走看看