0
点赞
收藏
分享

微信扫一扫

PAT_甲级_1130 中缀表达式 (25point(s))【中序遍历】


目录

​​1,题目描述​​

​​ 题目大意​​

​​2,思路​​

​​3,AC代码​​

​​4,解题过程​​

1,题目描述

PAT_甲级_1130 中缀表达式 (25point(s))【中序遍历】_C++

PAT_甲级_1130 中缀表达式 (25point(s))【中序遍历】_1130_02

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))

 题目大意

输出中缀表达式。注意每个子树(除了子树为单个key的情况)都需要用括号包起来。

 

2,思路

树的中序遍历。

注意什么时候输出括号即可:

PAT_甲级_1130 中缀表达式 (25point(s))【中序遍历】_C++_03

 

3,AC代码

#include<bits/stdc++.h>
using namespace std;
struct node{
string key;
int left, right;
};
bool notRoot[25];
vector<node> tree(25);
int N, a, b, root;
void inOrder(int r){
if(r == -1) return;
if((tree[r].left != -1 || tree[r].right != -1) && r != root)
printf("(");
inOrder(tree[r].left);
cout<<tree[r].key;
inOrder(tree[r].right);
if((tree[r].left != -1 || tree[r].right != -1) && r != root)
printf(")");
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf("%d\n", &N);
string key;
for(int i = 1; i <= N; i++){
cin>>key>>a>>b;
tree[i] = {key, a, b};// !!!i从1开始 不能用push_back
if(a != -1) notRoot[a] = true;
if(b != -1) notRoot[b] = true;
}
for(int i = 1; i <= N; i++){
if(!notRoot[i]){
root = i;
break;
}
}
inOrder(root);
return 0;
}

 

4,解题过程

编写过程中,每次运行都只出现一部分字符。。。

后来突然发现i从1开始,但是却是push_back,所以各节点都错位了。。。

PAT_甲级_1130 中缀表达式 (25point(s))【中序遍历】_C++_04

一发入魂o(* ̄▽ ̄*)ブ

PAT_甲级_1130 中缀表达式 (25point(s))【中序遍历】_甲级_05

举报

相关推荐

0 条评论