[关闭]
@2017libin 2019-06-16T16:55:32.000000Z 字数 1053 阅读 69

根据前序中序创建二叉树以及层次遍历输出镜像树

acm


  1. # include<iostream>
  2. # include<string>
  3. # include<algorithm>
  4. #include<numeric>
  5. #include <vector>
  6. #include <queue>
  7. using namespace std;
  8. int mid[32], fr[32];
  9. struct node {
  10. int l, r;
  11. }a[1002];
  12. //建一个以一个mid[la,ra],fr[lb,rb]所确定的数
  13. int build(int la, int ra, int lb, int rb)
  14. {
  15. if (la > ra)
  16. return 0;
  17. //fr:前序,b序列
  18. //mid:中序,a序列
  19. int rt = fr[lb], p1, p2;
  20. p1 = la;
  21. //找到pl对应的前序的第一个节点,也就是树的根。
  22. while (mid[p1] != rt) p1++;
  23. p2 = p1 - la;
  24. a[rt].l = build(la, p1 - 1, lb + 1, lb + p2);
  25. a[rt].r = build(p1 + 1, ra, lb + p2 + 1, rb);
  26. return rt;
  27. }
  28. void bfs(int x)
  29. {
  30. queue<int>q;
  31. queue<int>v;
  32. q.push(x);
  33. while (!q.empty())
  34. {
  35. int w = q.front();
  36. q.pop();
  37. //if (w == 0)
  38. // break;
  39. v.push(w);
  40. if (a[w].r != 0)
  41. q.push(a[w].r);
  42. if (a[w].l != 0)
  43. q.push(a[w].l);
  44. }
  45. while (!v.empty())
  46. {
  47. cout << v.front();
  48. v.pop();
  49. }
  50. return;
  51. }
  52. int main1()
  53. {
  54. int n;
  55. cin >> n;
  56. for (int i = 0; i < n; i++) cin >> mid[i];
  57. for (int i = 0; i < n; i++) cin >> fr[i];
  58. int root = build(0, n - 1, 0, n - 1);
  59. bfs(root);
  60. system("pause");
  61. return 0;
  62. }
  63. # include <stack>
  64. void test() {
  65. stack<int> s;
  66. priority_queue<int> q;
  67. for (int i = 1; i < 10; i++)
  68. s.push(i);
  69. for(int i = 1; i < 10; ++i)
  70. cout << s.top() << endl;
  71. q.push(1);
  72. cout << q.top() << endl;
  73. q.pop();
  74. cout << q.empty();
  75. }
  76. int main() {
  77. test();
  78. system("pause");
  79. return 0;
  80. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注