1130. Infix Expression (25)-PAT甲级真题(中序遍历)

题意

给定表达式的树,遍历一遍,得到中缀表达式,同时给中缀表达式加上括号。

思路

  • 构造静态链表
  • 存储、处理输入数据到rec
  • 设置fr数组寻找根
  • 构造中序遍历函数inorder
  • 输出

题解

#include<bits/stdc++.h>
using namespace std;
struct node{
	string str;
	int l, r;
}rec[21];
int n, r, fr[21];
string inorder(int s){
	if(rec[s].l == rec[s].r) return rec[s].str;
	else if(s == -1) return "";
	else return "(" + inorder(rec[s].l) + rec[s].str + inorder(rec[s].r) + ")";
}
int main(){
	cin>>n;
	for(int i = 1; i <= n; i ++){
		cin>>rec[i].str>>rec[i].l>>rec[i].r;
		if(rec[i].l != -1) fr[rec[i].l] = 1;
		if(rec[i].r != -1) fr[rec[i].r] = 1;
	}
	for(int i = 1; i <= n; i ++)
		if(fr[i] == 0) r = i;
	string ans = inorder(r);
	if(rec[r].l == rec[r].r) cout<<rec[r].str;
	else cout<<ans.substr(1, ans.size() - 2);
	return 0;
}

题目

Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 20) which is the total number of nodes in the syntax tree. Then N lines follow, each gives the information of a node (the i-th line corresponds to the i-th node) in the format:

data left_child right_child

where data is a string of no more than 10 characters, left_child and right_child are the indices of this node’s left and right children, respectively. The nodes are indexed from 1 to N. The NULL link is represented by −1. The figures 1 and 2 correspond to the samples 1 and 2, respectively.

infix1.JPG

infix2.JPG

Figure 1

Figure 2

Output Specification:

For each case, print in a line the infix expression, with parentheses reflecting the precedences of the operators. Note that there must be no extra parentheses for the final expression, as is shown by the samples. There must be no space between any symbols.

Sample Input 1:

8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1

Sample Output 1:

(a+b)*(c*(-d))

Sample Input 2:

8
2.35 -1 -1
* 6 1
- -1 4
% 7 8
+ 2 3
a -1 -1
str -1 -1
871 -1 -1

Sample Output 2:

(a*2.35)+(-(str%871))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
关于 Python 中的 `self` 关键字: 在 Python 中,`self` 是一个约定俗成的关键字,通常作为类方法的第一个参数出现。它表示类的实例对象本身,可以用来访问实例变量和方法。在 Python 中,不像其他语言中使用 `this` 或 `self` 关键字一样强制要求使用,但是为了代码的可读性和规范性,建议在类方法中使用 `self`。 关于 Python 实现中序遍历表达式二叉树,前缀、中缀、后缀表达式生成表达式二叉树: 以下是一个示例代码,实现了中序遍历表达式二叉树,前缀、中缀、后缀表达式生成表达式二叉树的功能: ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class ExpressionTree: def __init__(self): self.root = None # 中序遍历表达式二叉树 def inorder_traversal(self, node): if node.left: self.inorder_traversal(node.left) print(node.val, end=' ') if node.right: self.inorder_traversal(node.right) # 前缀表达式生成表达式二叉树 def build_from_prefix(self, expression): stack = [] for i in range(len(expression) - 1, -1, -1): if expression[i].isdigit(): node = TreeNode(expression[i]) stack.append(node) else: node = TreeNode(expression[i]) node.left = stack.pop() node.right = stack.pop() stack.append(node) self.root = stack.pop() # 中缀表达式生成表达式二叉树 def build_from_infix(self, expression): stack = [] i = 0 while i < len(expression): if expression[i].isdigit(): j = i while j < len(expression) and expression[j].isdigit(): j += 1 node = TreeNode(expression[i:j]) stack.append(node) i = j elif expression[i] == '(': stack.append('(') i += 1 elif expression[i] == ')': while stack[-1] != '(': right = stack.pop() op = stack.pop() left = stack.pop() node = TreeNode(op) node.left = left node.right = right stack.append(node) stack.pop() # 弹出左括号 i += 1 else: while stack and stack[-1] != '(' and self.precedence(stack[-1]) >= self.precedence(expression[i]): right = stack.pop() op = stack.pop() left = stack.pop() node = TreeNode(op) node.left = left node.right = right stack.append(node) stack.append(expression[i]) i += 1 while len(stack) > 1: right = stack.pop() op = stack.pop() left = stack.pop() node = TreeNode(op) node.left = left node.right = right stack.append(node) self.root = stack.pop() # 后缀表达式生成表达式二叉树 def build_from_postfix(self, expression): stack = [] for c in expression: if c.isdigit(): node = TreeNode(c) stack.append(node) else: right = stack.pop() left = stack.pop() node = TreeNode(c) node.left = left node.right = right stack.append(node) self.root = stack.pop() # 返回操作符优先级 def precedence(self, op): if op == '+' or op == '-': return 1 elif op == '*' or op == '/': return 2 else: return 0 ``` 其中,`TreeNode` 表示二叉树的节点,`ExpressionTree` 表示表达式二叉树。`build_from_prefix`、`build_from_infix`、`build_from_postfix` 分别表示通过前缀、中缀、后缀表达式生成表达式二叉树的方法。`inorder_traversal` 表示中序遍历表达式二叉树的方法。`precedence` 表示返回操作符优先级的方法。 示例代码中使用了栈来辅助实现表达式树的构建,具体的实现方法可以参考代码中的注释。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值