这个题目主要是对于单个孩子节点是先序遍历,需要区分下。
#include <iostream>
#include <algorithm>
using namespace std;
int const maxn = 25;
struct node{
string data;
int left = -1, right = -1;
}Node[maxn];
bool isroot[maxn] = {false};
void postorder(int root){
if(root == -1) return;
else if(Node[root].left == -1 || Node[root].right == -1){
printf("(%s", Node[root].data.c_str());
postorder(Node[root].left);
postorder(Node[root].right);
printf(")");
}else{
printf("(");
postorder(Node[root].left);
postorder(Node[root].right);
printf("%s)", Node[root].data.c_str());
}
}
int main(){
int n, root;
cin >> n;
for(int i = 1; i <= n; i++){
cin >> Node[i].data >> Node[i].left >> Node[i].right;
if(Node[i].left) isroot[Node[i].left] = true;
if(Node[i].right) isroot[Node[i].right] = true;
}
for(int i = 1; i <= n; i++){
if(isroot[i] == false) root = i;
}
postorder(root);
return 0;
}