1130 Infix Expression/表达式树、DFS

题目描述

在这里插入图片描述在这里插入图片描述在这里插入图片描述

题目大意

给定一棵表达式树,要求输出中缀表达式。

分析

类似于二叉树遍历的方法,将问题转化为求左子树的中缀表达式+根节点+右子树的中缀表达式,从而可以很好地使用递归算法解题。注意需要判断结点是否是叶子结点,是由于叶子结点的中缀表达式是不需要括号的。

#include<iostream>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
struct node {
	string s;
	int left, right;
}no[21];
int root;
bool ifshow[21];
string dfs(int index) {
	if (index == -1) return "";
	if (no[index].right != -1) {
		no[index].s = dfs(no[index].left) + no[index].s + dfs(no[index].right);
		if (index != root) no[index].s = "(" + no[index].s + ")";
	}	
	return no[index].s;
}
int main() {
#ifdef ONLINE_JUDGE
#else
	freopen("1.txt", "r", stdin);
#endif
	int n; cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> no[i].s >> no[i].left >> no[i].right;
		if (no[i].left != -1) ifshow[no[i].left] = 1;
		if (no[i].right != -1) ifshow[no[i].right] = 1;
	}
	for (root = 1; root <= n && ifshow[root]; root++);
	cout<<dfs(root);
	return 0;
}
发布了103 篇原创文章 · 获赞 9 · 访问量 4707

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104363538