1130 Infix Expression(25 分)

2018-08-25  本文已影响0人  zjh3029
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
#include <set>
using namespace std;

struct node
{
    string data;
    int left;
    int right;
    node(string a, int b, int c)
    {
        data = a;
        left = b;
        right = c;
    }
};
vector<node>vm;

int cnt = 0;
int dfs(int next,bool flag)
{
    if (vm[next].right == -1&&flag==false)
    {
        cout <<"("<<vm[next].data;
        return 0;
    }
    if (vm[next].right == -1 && flag ==true)
    {
        cout << vm[next].data<<")";
        while (cnt!=0)
        {
            cnt--;
            cout << ")";
        }
        cnt = 0;
        return 0;
    }
    if (vm[next].left != -1)
        dfs(vm[next].left - 1,false);
    if (vm[next].left == -1 && vm[next].right != -1)
    {
        cout << "(";
        cnt++;
    }
    cout << vm[next].data;
    dfs(vm[next].right-1,true);
    
}
int main()
{
    int M,b,c;
    string a;
    set<int>s;
    cin>>M ;
    for (int i = 0; i < M; i++)
    {
        cin >>a >> b >> c;
        node nn(a, b, c);
        vm.push_back(nn);
        s.insert(b);
        s.insert(c);
    }
    int start;
    for (int i = 1; i <=M; i++)
    {
        if (s.find(i) == s.end())
        {
            start = i;
            break;
        }
    }
    dfs(start - 1,false);
    system("pause");
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读