PAT(甲级)2019年秋季考试 7-3 Postfix Expression

#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
struct node{
    
    
	string s;
	int left, right;
}m[30];
bool vis[30];
string postT(int root)
{
    
    
	if(m[root].left == -1 && m[root].right == -1)
	return "(" + m[root].s + ")";
	else if(m[root].left == -1 && m[root].right != -1)
	return "(" + m[root].s + postT(m[root].right) + ")";
	else if(m[root].left != -1 && m[root].right != -1)
	return "(" + postT(m[root].left) + postT(m[root].right) + m[root].s + ")";
}
int main()
{
    
    
	int n;
	scanf("%d", &n);
	for(int i = 1; i <= n; i++)
	{
    
    
		string data;
		cin >> m[i].s;
		scanf("%d%d", &m[i].left, &m[i].right);
		if(m[i].left != -1)
		vis[m[i].left] = true;
		if(m[i].right != -1)
		vis[m[i].right] = true;
	}
	int root = 1;
	while(vis[root] == true && root <= n)
	root++;
	string res = postT(root);
	cout << res << endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_45486992/article/details/108391583