PAT甲级 1130 Infix Expression 25分 dfs

题目来源

https://pintia.cn/problem-sets/994805342720868352/problems/994805347921805312

分析

详解:https://www.liuchuo.net/archives/3798

本站类似题目(方法一样):https://blog.csdn.net/allisonshing/article/details/100642958

陷阱

题目说最后结果外面不要有括号。

Note that there must be no extra parentheses for the final expression, as is shown by the samples. 

满分代码

#include<iostream>
using namespace std;
struct node{
    string data;
    int l,r;
}a[30];
string dfs(int r){
    if(r==-1)return "";
    if(a[r].l==-1&&a[r].r!=-1)return "("+a[r].data+dfs(a[r].r)+")";
    if(a[r].l!=-1&&a[r].r!=-1)return "("+dfs(a[r].l)+a[r].data+dfs(a[r].r)+")";
    return a[r].data;
}
int main(){
    int n,have[100] = {0},root = 1;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i].data>>a[i].l>>a[i].r;
        if(a[i].l != -1) have[a[i].l] = 1;
        if(a[i].r != -1) have[a[i].r] = 1;
    }
    while(have[root] == 1) root++;
    string ans = dfs(root);
    if(ans[0] == '(') ans = ans.substr(1,ans.size()-2);
    cout << ans;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值