表达式树:输出中缀表达式

#include <stdio.h>
#include <stdlib.h>

typedef struct BiTNode{
    char data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

BiTree CreateBiTree( ){
    char ch;
    scanf("%c",&ch);
    if(ch=='#') return NULL;
    else{
        BiTree T = (BiTree)malloc(sizeof(BiTNode));
        T -> lchild  = T -> rchild = NULL;
        T->data = ch;
        T->lchild = CreateBiTree();
        T->rchild = CreateBiTree();
        return T;
    }

}

void ToExp( BiTree T ,int deep){
    if(T == NULL) return ;
    else if(T->lchild==NULL&&T->rchild==NULL)   //叶节点输出操作数
        printf("%c",T->data);
    else{
        if(deep>1) printf("(");                 //左子树有表达式,在输出运算符前加括号
        ToExp( T->lchild , deep +1 );
        printf("%c",T->data);
        ToExp( T->rchild , deep +1 );
        if(deep>1) printf(")");                 //右子树有表达式,在输出运算符后加括号
    }
}

void BTtoExp(BiTree T){
    ToExp( T , 1 );
}

int main(){
    printf("输入各节点:\n");
    BiTree T = CreateBiTree();
    printf("表达式树为:\n");
    BTtoExp(T);
}

猜你喜欢

转载自blog.csdn.net/RRWJ__/article/details/83043263