对于一棵二叉树而言,可以由其前序和中序或者中序和后序的遍历序列,确定一棵二叉树。
那么对于已知前序和中序序列,求后序序列也就是先还原二叉树,然后对其进行后序遍历即可。
二叉树结点的结构定义如下:
struct TreeNode { char value; TreeNode *leftChild; TreeNode *rightChild; };
实现代码如下:
#include <stdio.h> #include <string.h> #include <stdlib.h> TreeNode* allocateNode() { TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode)); node->leftChild = nullptr; node->rightChild = nullptr; return node; } char preStr[50], inStr[50]; void postOrder(TreeNode *T) { if (T->leftChild != nullptr) { postOrder(T->leftChild); } if (T->rightChild != nullptr) { postOrder(T->rightChild); } printf("%c ", T->value); } TreeNode* builtTree(int start1, int end1, int start2, int end2) { TreeNode *node = allocateNode(); node->value = preStr[start1]; int nodeIndex; for (int i = start2; i <= end2; ++i) if (preStr[start1] == inStr[i]) { nodeIndex = i; break; } if (nodeIndex != start2) { node->leftChild = builtTree(start1 + 1, start1 + (nodeIndex - start2), start2, nodeIndex - 1); } if (nodeIndex != end2) { node->rightChild = builtTree(start1 + (nodeIndex - start2) + 1, end1, nodeIndex + 1, end2); } return node; } void main(void) { scanf("%s",preStr); scanf("%s", inStr); int preLen = strlen(preStr); int inLen = strlen(inStr); TreeNode *root = builtTree(0, preLen - 1, 0, inLen - 1); postOrder(root); }
时间: 2024-12-26 17:04:31