-
Description:
-
Input a binary tree and output its image.
-
Input:
-
The input may contain multiple test examples. The input ends with EOF.
For each test case, the first input behavior is an integer N (0 <=n <= 1000, and N represents the number of Binary Tree nodes to be input (nodes start from 1 ). The next row contains N numbers, representing the value of the element of the I-th Binary Tree node. Next there are n rows, each row has a letter CI.
Ci = 'D' indicates that the I node has two children, followed by the left and right children numbers.
Ci = 'l' indicates that the I node has a left child followed by the ID of the left child.
Ci = 'R' indicates that the I node has a right child followed by the number of the right child.
Ci = 'Z' indicates that no child exists on the I node.
-
Output:
-
Corresponding to each test case,
Output the element values of the child node in the forward order.
If it is null, the output is null.
-
Sample input:
-
78 6 10 5 7 9 11d 2 3d 4 5d 6 7zzzz
-
Sample output:
-
8 10 11 9 6 7 5
The idea is simple. Just simulate it again. Tree Structure is unnecessary. when outputting data, you can first right and then left.
#include <stdio.h>int n, a, i;typedef struct Node {struct Node * l;struct Node * r;int data;}* pNode, Node;char temp[2];Node tree[1001];void print(pNode root) {if (root == 0)return;printf(" %d", root->data);print(root->r);print(root->l);}int main() {while (~scanf("%d", &n)) {for ( i = 1; i <= n; i++) {scanf("%d", &tree[i].data);tree[i].l = tree[i].r = 0;}for ( i = 1; i <= n; i++) {scanf("%s %d", temp, &a);if (temp[0] == 'd') {tree[i].l = &tree[a];scanf("%d", &a);tree[i].r = &tree[a];}else if(temp[0] == 'l')tree[i].l = &tree[a];else if(temp[0] == 'r')tree[i].r = &tree[a];}if (n) {printf("%d", tree[1].data);print(tree[1].r);print(tree[1].l);puts("");} elseputs("NULL");}return 0;}