And binary tree operation (b)

Exchange left and right subtrees of all nodes

void swaptree(BiTree &T){
    BiTree temp;
    if(T){
        swaptree(T->lchild);
        swaptree(T->rchild);
        temp=T->lchild;
        T->lchild=T->rchild;
        T->rchild=temp;
    }
}

Analyzing two trees are similar (only the root node or empty)

int similartree(BiTree &T1,BiTree &T2){
    int s1,s2;
    if(T1==NULL&&T2==NULL){
        return 1;
    }
    if(T1==NULL||T2==NULL){
        return 0;
    }
    s1=similartree(T1->lchild,T2->rchild);
    s2=similartree(T2->lchild,T2->rchild);
    return s1*s2;
}

Given expression tree will be converted to equivalent infix

void BitreeToExp(BiTree &T,int depth){
    if(T==NULL) return;
    if(T->lchild==NULL&&T->rchild==NULL){
        cout<<T->data;//输出操作数
    }
    else{
        if(depth>1){cout<<'(';}
        BitreeToExp(T->lchild,depth+1);
        cout<<T->data;//输出操作符
        BitreeToExp(T->rchild,depth+1);
        if(depth>1){cout<<' ) ' ;} // if one sub-expression is increased to a bracket 
    } 
} 
void BitreeToE (BiTree & T) { 
    BitreeToExp (T, . 1 ); 
}

 

Guess you like

Origin www.cnblogs.com/Yshun/p/11628497.html