zoukankan      html  css  js  c++  java
  • 二叉搜索树的建树与遍历

    注意要插入的值,如果等于当前节点,就把它变成当前节点的右儿子

    此代码是中南大学暑训入门 B题的AC代码

    #include<iostream>
    #define ll long long
    using namespace std;
    struct node
    {
        ll data;
        node * lson;
        node * rson;
    }*head;
    int t;
    
    void build(ll x,node *p)
    {
        if(p==NULL){
            node * pp;
            pp=new node ;
            pp->data=x;
            pp->lson=NULL;
            pp->rson=NULL;
            head=pp;
            return;
        }
    
        if(p->data<=x&&p->rson){build(x,p->rson);}
        else if(p->data>x&&p->lson){build(x,p->lson);}
        else if(p->data<=x&&!p->rson){
            node * pp;
            pp=new node ;
            pp->data=x;
            pp->lson=NULL;
            pp->rson=NULL;
            p->rson=pp;
        }
        else if(p->data>x&&!p->lson){
            node * pp;
            pp=new node ;
            pp->data=x;
            pp->lson=NULL;
            pp->rson=NULL;
            p->lson=pp;
        }
    }
    
    void preview(node *p)
    {
        if(p==NULL){return;}
        if(t){cout<<" ";}
        cout<<p->data;t++;
        preview(p->lson);
        preview(p->rson);
    }
    
    void midview(node *p)
    {
        if(p==NULL){return;}
        midview(p->lson);
        if(t)cout<<" ";
        cout<<p->data;t++;
        midview(p->rson);
    }
    
    void posview(node *p)
    {
    
        if(p==NULL){return;}
        posview(p->lson);
        posview(p->rson);
        if(t){cout<<" ";}
        cout<<p->data;t++;
    }
    
    void delet(node *p)
    {
    
        if(p==NULL){return;}
        delet(p->lson);
        delet(p->rson);
        delete p;
    
    }
    
    int main()
    {
        int T;
        while(cin>>T)
        while(T--){
            int n;
            ll x;
            cin>>n;
            head=NULL;
            for(int i=0;i<n;i++){
                cin>>x;
                build(x,head);
            }
            t=0;
            preview(head);
            cout<<endl;
            t=0;
            midview(head);
            cout<<endl;
            t=0;
            posview(head);
            cout<<endl;
            delet(head);
            cout<<endl;
        }
    }
    

      

  • 相关阅读:
    java7-4 继承的练习
    java7-3 继承
    cocos2d-x之计时器初试
    cocos2d-x之物理按键初试
    cocos2d-x之加速度传感器初试
    cocos2d-x之多点触碰初试
    cocos2d-x之事件传递
    cocos2d-x之单点触碰初试
    cocos2d-x之value
    cocos2d-x之Vector与map
  • 原文地址:https://www.cnblogs.com/ZGQblogs/p/9095867.html
Copyright © 2011-2022 走看看