#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
string data;
int left,right;
};
vector<node>v;
string dfs(int root){
if(v[root].left==-1&&v[root].right==-1) return v[root].data;
if(v[root].left==-1&&v[root].right!=-1) return "("+v[root].data+dfs(v[root].right)+")"; //-(v[root].right)
if(v[root].left!=-1&&v[root].right!=-1) return "("+dfs(v[root].left)+v[root].data+dfs(v[root].right)+")";
}
int main(){
int n,have[100]={0},root=1;
cin>>n;
v.resize(n+1);
for(int i=1;i<=n;i++){
cin>>v[i].data>>v[i].left>>v[i].right;
if(v[i].left!=-1) have[v[i].left]=1;
if(v[i].right!=-1) have[v[i].right]=1;
}
while(have[root]==1) root++; //寻找根节点
string ans=dfs(root);
if(ans[0] == '(') ans = ans.substr(1,ans.size()-2); //去掉最外层的括号
cout<<ans;
system("pause");
return 0;
}
PAT 1130 Infix Expression (25 分) dfs或中序遍历
于 2022-02-05 22:27:34 首次发布