PaintAVL

 

// PaintAVL
void OutNode(AVLNode * node,int cor){ 
    for(int i=cor;i<node->blank;i++) printf(" "); 
    cout<<node->val; 
} 
int CalCor(AVLNode * root,int lst){
    Nil(); root->blank=0;
    root->len=root->val.length(); int dis=0,dis2=0;;
    if(root->chi[0]!=nil){ root->chi[0]->hei=root->hei+1; dis=CalCor(root->chi[0],lst); }
    int halflen=(root->len)/2;  root->blank=lst+dis-halflen; if(root->blank<lst) root->blank=lst;
    if(root->chi[1]!=nil){ root->chi[1]->hei=root->hei+1; dis2=CalCor(root->chi[1],lst+dis+(dis?1:0)); }
    if(!dis2) root->blank-=(root->len+1)/2;  if(root->blank<lst) root->blank=lst;
    int ans=((dis+(dis?1:0)+dis2)>root->len)?dis+(dis?1:0)+dis2:root->len;
    if(dis2 && dis && (root->chi[1]->blank-root->chi[0]->blank)>root->len && (root->chi[0]->blank+root->chi[1]->blank)/2+root->len<=ans) 
        root->blank=(root->chi[0]->blank+root->chi[1]->blank)/2;
    return ans; Nil();
} 
void OutTree(AVLNode * root){ 
    queue<AVLNode *> q; 
    q.push(root); int y=0,cor=0,cor2=0,cor3=0; string branch="",pro="";
    while(!q.empty()){ 
        AVLNode* t=q.front();  
        if(t->hei!=y) { cout<<endl<<pro<<endl<<branch; branch=""; pro=""; y=t->hei; printf("\n"); cor=0; cor2=0; cor3=0; } 
        OutNode(t,cor); cor=t->blank+t->len;
        for(int i=cor3;i<t->blank;i++) pro+=' '; cor3=t->blank;
        switch(t->bf){
            case -1: pro+="-1  "; cor3+=4; break;
            case -2: pro+="-2  "; cor3+=4; break;
            case 0:  pro+="0  "; cor3+=3; break;
            case 1:  pro+="1  "; cor3+=3; break;
            case 2:  pro+="2  "; cor3+=3; break;
        }
        if(t->chi[0]!=nil){ 
            q.push(t->chi[0]); 
            for(int i=cor2;i<(t->chi[0]->blank+t->blank)/2;i++) branch+=' '; 
            branch+='/'; cor2=(t->chi[0]->blank+t->blank)/2; 
 
        }
        if(t->chi[1]!=nil){ 
            q.push(t->chi[1]); 
            for(int i=cor2;i<(t->chi[1]->blank+t->blank)/2;i++) branch+=' '; 
            branch+='\\'; cor2=(t->chi[1]->blank+t->blank)/2; 
        }
        q.pop(); 
    } cout<<endl<<pro;
} 
void Doit(){ 
    root->hei=0; 
    CalCor(root,0);
    OutTree(root); 
    printf("\n//////////////////////////////////\n"); 
} 

  

posted on 2013-08-18 13:07  Amyc  阅读(171)  评论(0)    收藏  举报