题目:知道一棵二叉树的前序序列、中序系列,打印出它的后序系列
下面算法的时间复杂度:O(n^2) -- 最坏情况就是左单支树
/* Kown the preorder listing and the inorder listing of a tree, print it's postorder listing */ void PrintPostOrder(const char *pre, int s1, int e1, const char *in, int s2, int e2) { if (s1 > e1 || s2 > e2) return; char root = pre[s1]; for (int i=s2; i<=e2; i++) if (in[i] == root) break; int offset = i-s2; PrintPostOrder(pre, s1+1, s1+offset, in, s2, i-1); PrintPostOrder(pre, s1+offset+1, e1, in, i+1, e2); printf("%c", root); } int main() { const char *pre="ABCDEF"; const char *in="FEDCBA"; printf("PreOrder : %s\n", pre); printf("InOrder : %s\n", in); printf("PostOrder: "); PrintPostOrder(pre, 0, strlen(pre)-1, in, 0, strlen(in)-1); printf("\n"); return 0; }