题目描述
知识点: 树的中序遍历
思路: 具体思路就是中序遍历这课树。然后对遍历左子树完毕后加括号,右子树同理。如果是叶节点就不用加。
#include<iostream>
using namespace std;
const int N = 25;
int l[N],r[N];
string e[N];
int n,root;
bool st[N],is_leaf[N];
string dfs(int u){
string left,right;
if(l[u] != -1){
left = dfs(l[u]);
if(!is_leaf[l[u]])
left = "(" + left + ")";
}
if(r[u] != -1){
right = dfs(r[u]);
if(!is_leaf[r[u]])
right = "(" + right + ")";
}
return left + e[u] + right;
}
int main(){
cin>>n;
for(int i = 1;i <= n;i++){
cin>>e[i]>>l[i]>>r[i];
if(l[i] != -1) st[l[i]] = true;
if(r[i] != -1) st[r[i]] = true;
if(l[i] == -1 && r[i] == -1) is_leaf[i] = true;
}
root = 1;
while(st[root]) root++;
cout<<dfs(root);
return 0;
}