[关闭]
@DingCao-HJJ 2015-09-30T16:00:12.000000Z 字数 2126 阅读 1456

sicily_1156 Binary tree

sicily 二叉树


题目

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

Your task is very simple: Given a binary tree, every node of which contains one upper case character (‘A’ to ‘Z’); you just need to print all characters of this tree in pre-order.

Input

Input may contain several test data sets.

For each test data set, first comes one integer n (1 <= n <= 1000) in one line representing the number of nodes in the tree. Then n lines follow, each of them contains information of one tree node. One line consist of four members in order: i (integer, represents the identifier of this node, 1 <= i <= 1000, unique in this test data set), c (char, represents the content of this node described as above, ‘A’ <= c <= ‘Z’), l (integer, represents the identifier of the left child of this node, 0 <= l <= 1000, note that when l is 0 it means that there is no left child of this node), r (integer, represents the identifier of the right child of this node, 0 <= r <= 1000, note that when r is 0 it means that there is no right child of this node). These four members are separated by one space.

Input is ended by EOF.

You can assume that all inputs are valid. All nodes can form only one valid binary tree in every test data set.

Output

For every test data set, please traverse the given tree and print the content of each node in pre-order. Characters should be printed in one line without any separating space.

Sample Input

3
4 C 1 3
1 A 0 0
3 B 0 0
1
1000 Z 0 0
3
1 Q 0 2
2 W 3 0
3 Q 0 0

Sample Output

CAB
Z
QWQ

题目大意

根据给出的数据构建一棵二叉树

思路

本题没有说明根一定在第一个,所以要自行找出根的序号。一个比较简便的方法是把所有的出现过的节点的序号进行异或操作,那么仅仅出现过一次的就是根了。

代码

  1. // Copyright (c) Junjie_Huang@SYSU(SNO:13331087). All Rgights Reserved.
  2. // 1156.cpp: http://soj.sysu.edu.cn/1156
  3. #include <cstdio>
  4. #include <cstring>
  5. #define MAX_SIZE 1000
  6. struct Node {
  7. char data;
  8. int left;
  9. int right;
  10. };
  11. void pre_order(Node node[],int index) {
  12. if (node[index].data) {
  13. printf("%c", node[index].data);
  14. pre_order(node, node[index].left);
  15. pre_order(node, node[index].right);
  16. }
  17. }
  18. int main() {
  19. int n = 0;
  20. Node tree[MAX_SIZE + 10];
  21. while (scanf("%d", &n) != EOF) {
  22. memset(tree, 0, sizeof(tree));
  23. int root = 0, index = 0;
  24. for (int i = 0; i < n; i++) {
  25. scanf("%d ", &index);
  26. scanf("%c %d %d",
  27. &tree[index].data, &tree[index].left, &tree[index].right);
  28. // finds the root node
  29. // because the root only appears once while the rest node will appear
  30. // twice and by the EOR operation, the number left finally must the root.
  31. root = root ^ index ^ tree[index].left ^ tree[index].right;
  32. }
  33. pre_order(tree, root);
  34. printf("\n");
  35. }
  36. return 0;
  37. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注