int InOrder[1000], PosterOrder[1000]; typedef struct BiTNode { int data; struct BiTNode *LChild, *RChild; } BiTNode, *BiTree; int find(int *InOrder, int &x, int n) { for(int i = 0; i< n; ++i) {if(InOrder[i] == x) return i;} return -1; } void PreOrderTraverse(BiTree T, int n) { if(T == NULL) return ; printf("%d ", T -> data); PreOrderTraverse(T -> LChild, n); PreOrderTraverse(T -> RChild, n); } BiTNode *CreateInTree(int *PosterOrder, int *InOrder, int n) { BiTNode *in; if(PosterOrder == NULL || InOrder == NULL || n ==0) return NULL; else { in = (BiTNode *)malloc(sizeof(BiTNode)); in -> data = PosterOrder[n - 1]; int i = find(InOrder, PosterOrder[n - 1], n); if(i != -1) { in -> LChild = CreateInTree(PosterOrder, InOrder, i); in -> RChild = CreateInTree(PosterOrder + i, InOrder + i + 1, n - i - 1); return in; } return NULL; } } void destoryBiTree(BiTree &T) { if(T == NULL) return ; destoryBiTree(T -> LChild); destoryBiTree(T -> RChild); free(T); T = NULL; } int main(int argc, char *argv[]) { BiTree T; int n, i; while(scanf("%d", &n) != EOF) { for(i = 0; i < n; i++) scanf("%d", &PosterOrder[i]); for(i = 0; i < n; i++) scanf("%d", &InOrder[i]); T = CreateInTree(PosterOrder, InOrder, n); PreOrderTraverse(T, n); destoryBiTree(T); puts(""); } return 0; } 7 3 1 2 5 6 7 4 3 2 1 4 5 7 6 4 2 3 1 7 5 6
时间: 2024-11-05 11:31:07