#include <iostream> #include <cstdio> using namespace std; typedef struct BiTNode { int data; struct BiTNode *lchild, *rchild; }BiTNode, *BiTree; BiTree PreInCreate(char A[], char B[], int l1, int h1, int l2, int h2) { BiTNode *root = (BiTNode *)malloc(sizeof(BiTNode)); root->data = A[l1]; int i; for(i = l2; B[i] != root->data; i++); int llen = i - l2; int rlen = h2 - i; if(llen){ root->lchild = PreInCreate(A, B, l1+1, l1+llen, l2, l2+llen-1); } else { root->lchild = NULL; } if(rlen) { root->rchild = PreInCreate(A, B, h1-rlen+1, h1, h2-rlen+1, h2); } else { root->rchild = NULL; } return root; } void PreOrder(BiTree T) { if(T != NULL) { printf("%c ", T->data); PreOrder(T->lchild); PreOrder(T->rchild); } } void InOrder(BiTree T) { if(T != NULL) { InOrder(T->lchild); printf("%c ", T->data); InOrder(T->rchild); } } int main() { char A[100], B[100]; printf("please input preorder and inorder :\n"); scanf("%s%s", A+1, B+1); A[0] = A[0] = 'a'; int len = strlen(A)-1; BiTNode * root = PreInCreate(A, B, 1, len, 1, len); PreOrder(root); cout << endl; InOrder(root); return 0; } /** Test: 124356 421536 **/
时间: 2024-10-09 12:22:24