目錄
1,題目描述
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,思路
樹的中序遍歷。
注意什麼時候輸出括號即可:
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,所以各節點都錯位了。。。
一發入魂o(* ̄▽ ̄*)ブ