考点:二叉树的建立,遍历DFS
注意点:要考虑到只有一个孩子的时候是先序遍历,两个孩子是后序遍历,也就是读懂题很重要。with parentheses reflecting the precedences of the operators.(括号反应优先级)
#include <iostream>
using namespace std;
const int maxn = 100;
struct node{
string v;
int lchild,rchild;
}tree[maxn];
bool inq[maxn] = {false};
void postOrder(int root){
if(root==-1) return;
cout<<"(";
if(tree[root].lchild == -1 || tree[root].rchild == -1){
cout<<tree[root].v;
}
postOrder(tree[root].lchild);
postOrder(tree[root].rchild);
if(tree[root].lchild !=-1 && tree[root].rchild!=-1){
cout<<tree[root].v;
}
cout<<")";
}
int main() {
int root,n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>tree[i].v>>tree[i].lchild>>tree[i].rchild;
if(tree[i].lchild !=-1) inq[tree[i].lchild] = true;
if(tree[i].rchild !=-1) inq[tree[i].rchild] = true;
}
for(int i=1;i<=n;i++) if(inq[i]==false) root = i;
postOrder(root);
return 0;
}