后缀表达式树

来源:互联网 发布:淘宝活动派发报名任务 编辑:程序博客网 时间:2024/06/16 19:25

水平有限,代码粗糙。。。。。。。


构造表达式树后用中序遍历输出结果。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <stack>
using namespace std;
const int MAX =100;


struct node
{
    char data;
    struct node *l;
    struct node *r;
};


stack <node *> S;


node *creattree()
{
    char x;
    while(scanf("%s",&x)&&x!='#')
    {
        if(x=='+'||x=='*')
        {
            node *t=new node;
            t->data=x;
            t->l=NULL;
            t->r=NULL;
            node *T1=S.top();
            S.pop();
            node *T2=S.top();
            S.pop();
            t->l=T2;
            t->r=T1;
            S.push(t);
        }
        else
        {
            node *t=new node;
            t->data=x;
            t->l=NULL;
            t->r=NULL;
            S.push(t);
        }
    }
    node *tt=S.top();
    S.pop();
    return  tt;
}


void zxp(node *T)
{
    if(T!=NULL)
    {
        zxp(T->l);
        cout<<T->data<<" ";
        zxp(T->r);
    }
}
int main()
{
    node *T=NULL;
    T=creattree();
    zxp(T);
}

0 0
原创粉丝点击