• 3.二叉树遍历序列还原


    题目

    给出二叉树的中序遍历序列和后序遍历序列,编程还原该二叉树。

    输入:
      第1行为二叉树的中序遍历序列
      第2行为二叉树的后序遍历序列

    输出:
      二叉树的按层遍历序列

    C++代码

    1. #include
    2. using namespace std;
    3. struct Node
    4. {
    5. char data;
    6. Node* left;
    7. Node* right;
    8. };
    9. // 创建新节点
    10. Node* NewNode(char data)
    11. {
    12. Node* node = new Node;
    13. node->data = data;
    14. node->left = NULL;
    15. node->right = NULL;
    16. return node;
    17. }
    18. // 找到在中序遍历序列中的索引位置
    19. int Search(string in, int start, int end, char value)
    20. {
    21. int i;
    22. for (i = start; i <= end; i++)
    23. {
    24. if (in[i] == value) {
    25. return i;
    26. }
    27. }
    28. return i;
    29. }
    30. // 使用中序和后序遍历序列构建二叉树
    31. Node* BuildTree(string in, string post, int inStart, int inEnd)
    32. {
    33. static int postIndex = inEnd;
    34. if (inStart > inEnd) {
    35. return NULL;
    36. }
    37. // 创建新的节点,postIndex位置是根节点
    38. Node* node = NewNode(post[postIndex--]);
    39. if (inStart == inEnd) {
    40. return node;
    41. }
    42. // 在中序数组中找到此节点的索引
    43. int inIndex = Search(in, inStart, inEnd, node->data);
    44. // 递归构建左右子树
    45. node->right = BuildTree(in, post, inIndex + 1, inEnd);
    46. node->left = BuildTree(in, post, inStart, inIndex - 1);
    47. return node;
    48. }
    49. // 打印层次遍历序列
    50. void PrintLevelOrder(Node* root)
    51. {
    52. if (root == NULL) return;
    53. queue q;
    54. q.push(root);
    55. while (!q.empty())
    56. {
    57. int nodeCount = q.size();
    58. while (nodeCount > 0)
    59. {
    60. Node* node = q.front();
    61. cout << node->data;
    62. q.pop();
    63. if (node->left != NULL)
    64. q.push(node->left);
    65. if (node->right != NULL)
    66. q.push(node->right);
    67. nodeCount--;
    68. }
    69. }
    70. cout << endl;
    71. }
    72. // 主函数
    73. int main()
    74. {
    75. string in;
    76. string post;
    77. cin >> in >> post;
    78. int len = in.size();
    79. Node* root = BuildTree(in, post, 0, len - 1);
    80. PrintLevelOrder(root);
    81. return 0;
    82. }

  • 相关阅读:
    proto转java类时相关option配置
    菜谱APP源码和设计报告
    Scala基础教程--13--函数进阶
    Zookeeper概述
    SpringMVC源码分析(二)启动过程之RequestMappingHandlerMapping分析
    软考高级软件架构师论文——论软件架构评估
    Node.js安装与配置+ MYSQL使用 (详细步骤)
    C++栈解决括号匹配问题、逆波兰表达式问题
    mysql14
    Promise.allSettled 的 Polyfill 处理
  • 原文地址:https://blog.csdn.net/m0_74200772/article/details/133799554