当前位置:   article > 正文

pta 7-4 树的遍历_pta7-4 根到结点的路径利用二叉树后序遍历算法,输出从根到某个结点的路径。输入是

pta7-4 根到结点的路径利用二叉树后序遍历算法,输出从根到某个结点的路径。输入是
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef struct node *tree;
  4. struct node
  5. {
  6. int data;
  7. tree left, right;
  8. };
  9. tree build(int in[], int pos[], int n)
  10. {
  11. tree t;
  12. if (!n)
  13. return NULL;
  14. t = (tree)malloc(sizeof(struct node));
  15. t->data = pos[n - 1];
  16. t->left = t->right = NULL;
  17. int i;
  18. for (i = 0; i < n; i++)
  19. {
  20. if (pos[n - 1] == in[i])
  21. break;
  22. }
  23. t->left = build(in, pos, i);
  24. t->right = build(in + i + 1, pos + i, n - i - 1);
  25. return t;
  26. }
  27. void cengci(tree t, int n)
  28. {
  29. tree q[100], p;
  30. int ll = 0;
  31. int rr = 0;
  32. int len = 0;
  33. if (n)
  34. {
  35. q[rr++] = t;
  36. while (ll != rr)
  37. {
  38. p = q[ll++];
  39. cout << p->data;
  40. len++;
  41. if (len != n)
  42. cout << " ";
  43. else
  44. {
  45. cout << endl;
  46. }
  47. if (p->left != NULL)
  48. {
  49. q[rr++] = p->left;
  50. }
  51. if (p->right != NULL)
  52. {
  53. q[rr++] = p->right;
  54. }
  55. }
  56. }
  57. }
  58. int main()
  59. {
  60. int n;
  61. cin >> n;
  62. int in[31], pos[31];
  63. for (int i = 0; i < n; i++)
  64. {
  65. cin >> pos[i];
  66. }
  67. for (int i = 0; i < n; i++)
  68. {
  69. cin >> in[i];
  70. }
  71. tree t;
  72. t = build(in, pos, n);
  73. cengci(t, n);
  74. return 0;
  75. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/681771
推荐阅读
相关标签
  

闽ICP备14008679号