Uva12219 递归打印树和构建表达式树

#include<cstdio>
#include<map>
#include<string>
#include<iostream>
using namespace std;
struct T{
    string s;
    int ls,rs;
    bool operator < (const T& rhs) const//要用map一定要重载运算符。
    {
        if(s!=rhs.s) return s<rhs.s;
        else if(ls!=rhs.ls) return ls<rhs.ls;
        else return rs<rhs.rs;
    }
};
map<int,T> tree;
map<T,int> save;
map<int,int>old;
string str;
int k,p;
int build(){
    int u=++k;
    string s1;
    while(str[p]>='a'&&str[p]<='z')s1+=str[p++];
    T& t=tree[u];
    t.s=s1;
    t.ls=0;
    t.rs=0;
    if(str[p]=='('){
        p++;
        t.ls=build();p++;
        t.rs=build();p++;
    }
    //不减就是对每一个字符建立节点,相减就会抛弃掉已经建立的节点
    if(save[t]){
        k--;
        return save[t];
    }
    else save[t]=u;
    return u;
}
//递归打印树
//递归栈每次只能处理本层的一个节点,他可以通过下一个递归找到他的子节点(子树的根节点)通过return
//返回给他的根节点作为自己点,通过cnt--去点该节点(下次重新赋值实现,通过cnt++增加节点(编号一个节点)
//递归要深入到最深层的子树结构来看处理模式,最深层处理对了那么整棵树就处理对了。
void print(int u){
    //已经打印一次节点就打印他的子树编号
    if(old[u])printf("%d",u);
    else{
        old[u]=1;
        cout<<tree[u].s;
        if(tree[u].ls){
            cout<<"(";
            print(tree[u].ls);//打印左子树
            cout<<",";
            print(tree[u].rs);//打印右子树
            cout<<")";
        }
    }
}
int main(){
    int a;
    cin>>a;
    while(a--){
        old.clear();
        save.clear();
        tree.clear();
        cin>>str;
        k=p=0;
        print(build());
        cout<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值