其他分享
首页 > 其他分享> > 中缀表达式

中缀表达式

作者:互联网

https://www.acwing.com/problem/content/1625/

思路:
注意这题dfs的写法,值得学习。

#include <iostream>

using namespace std;

const int N = 25;

int n;
int l[N], r[N];
string w[N];
bool st[N], is_leaf[N];

string dfs(int u)
{
    string left, right;
    if (l[u] != -1)
    {
        left = dfs(l[u]);
        if (!is_leaf[l[u]]) left = "(" + left + ")";
    }
    if (r[u] != -1)
    {
        right = dfs(r[u]);
        if (!is_leaf[r[u]]) right = "(" + right + ")";
    }

    return left + w[u] + right;
}

int main()
{
    cin >> n;
    for (int i = 1; i <= n; i ++ )
    {
        cin >> w[i] >> l[i] >> r[i];
        if (l[i]) st[l[i]] = true;
        if (r[i]) st[r[i]] = true;

        if (l[i] == -1 && r[i] == -1) is_leaf[i] = true;
    }

    int root = 1;
    while (st[root]) root ++ ;

    cout << dfs(root) << endl;

    return 0;
}

标签:right,leaf,中缀,int,dfs,st,表达式,left
来源: https://www.cnblogs.com/xjtfate/p/16603354.html