[关闭]
@DingCao-HJJ 2015-08-29T15:06:52.000000Z 字数 1761 阅读 1037

sicily_1935_重建二叉树解题报告

sicily 二叉树


传送门:http://soj.sysu.edu.cn/1935

  1. // Copyright (c) Junjie_Huang@SYSU(SNO:13331087). All Rgights Reserved.
  2. // 1000_sicily_1935.cpp: http://soj.sysu.edu.cn/1935
  3. #include
  4. #include
  5. #include
  6. #include
  7. #include
  8. #define MAX_SIZE 1000
  9. #define STRING_SIZE 50
  10. using std::cin;
  11. using std::string;
  12. using std::queue;
  13. // Pre:
  14. // @|tree[]|: the array needs to traverse
  15. // @|pre|: the string printed by traversing a tree in pre-order
  16. // @|mid|: the string printed by traversing a tree in mid-order
  17. // @|index|: the index of parent node in the |tree[]|.
  18. // Post: None
  19. // Usage: finds the root node of a tree and sperates the |mid| with root so we
  20. // can point out the left sub-tree and the right one. Recurses the function
  21. // until all the elements are insert to the |tree|
  22. void rebuild(char tree[], string pre, string mid, int index = 0) {
  23. // records the left child |left| and the right child |right|
  24. // of the parent node
  25. int left = 2 * index + 1, right = 2 * index + 2;
  26. if (pre.length()) { // Recursions end when all the elements are inserted.
  27. tree[index] = pre[0]; // insert the data of the parent node
  28. // finds the position of root node from |mid|
  29. int temp = mid.find(pre[0]);
  30. // Recursions. Seperates the tree to its left sub-tree and the right one.
  31. // and the |left| and |right| will be the new parent nodes.
  32. rebuild(tree, pre.substr(1, temp), mid.substr(0, temp), left);
  33. rebuild(tree, pre.substr(temp + 1), mid.substr(temp + 1), right);
  34. }
  35. }
  36. // Pre:
  37. // @|tree[]|: the binary tree we want to traverse with BFS. Here because
  38. // we use an array to store the data, so we just need to traverse the array
  39. // by the index.
  40. // Post: Node
  41. void BFS_visit(char tree[]) {
  42. for (int i = 0; i < MAX_SIZE; i++) {
  43. if (tree[i]) printf("%c", tree[i]);
  44. }
  45. printf("\n");
  46. }
  47. int main() {
  48. int n = 0;
  49. char tree[MAX_SIZE + 10];
  50. for (scanf("%d", &n); n; n--) {
  51. memset(tree, 0, sizeof(tree));
  52. string pre_order, mid_order;
  53. cin >> pre_order >> mid_order;
  54. rebuild(tree, pre_order, mid_order);
  55. BFS_visit(tree);
  56. }
  57. return 0;
  58. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注