-
输入:
-
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000,n代表将要输入的二叉树节点的个数(节点从1开始编号)。接下来一行有n个数字,代表第i个二叉树节点的元素的值。接下来有n行,每行有一个字母Ci。
Ci=’d’表示第i个节点有两子孩子,紧接着是左孩子编号和右孩子编号。
Ci=’l’表示第i个节点有一个左孩子,紧接着是左孩子的编号。
Ci=’r’表示第i个节点有一个右孩子,紧接着是右孩子的编号。
Ci=’z’表示第i个节点没有子孩子。
-
输出:
-
对应每个测试案例,
按照前序输出其孩子节点的元素值。
若为空输出NULL。
-
样例输入:
-
7 8 6 10 5 7 9 11 d 2 3 d 4 5 d 6 7 z z z z
-
样例输出:
-
8 10 11 9 6 7 5
#include <cstdio> #include <iostream> #include <list> using namespace std; struct Node{ int x; struct Node *left,*right; }; bool firstprint; Node* mirror(Node *root){ if(root == NULL) return NULL; Node *left = mirror(root->left); Node *right = mirror(root->right); root->left = right; root->right = left; return root; } void print(Node *root){ if(root){ if(firstprint == true) { printf("%d",root->x); firstprint = false ; } else printf(" %d",root->x); print(root->left); print(root->right); } } int main(int argc, char const *argv[]) { int n,l,r; char c[5]; Node *A[1010]; while(scanf("%d",&n) != EOF){ A[1] = NULL; firstprint = true; for(int i = 1;i <=n;i++){ Node *p = new Node; scanf("%d",&p->x); p->left = p->right = NULL; A[i] = p; } for(int i = 1;i <= n;i++){ scanf("%s",c); if(c[0] == 'd'){ scanf("%d %d",&l,&r); A[i]->left = A[l]; A[i]->right = A[r]; } else if(c[0] == 'l'){ scanf("%d",&l); A[i]->left = A[l]; } else if(c[0] == 'r'){ scanf("%d",&r); A[i]->right = A[r]; }else{ continue; } } if(A[1] == NULL){ printf("NULL\n"); continue; } mirror(A[1]); print(A[1]); printf("\n"); } return 0; }