1. 程式人生 > >面試經典&&競賽——二叉樹

面試經典&&競賽——二叉樹

To record her trees for future generations, she wrote down two strings for each tree: a preorder traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree). For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG. 
She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried it). 

Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed possible, but only because she never had used the same letter twice in the same tree. 
However, doing the reconstruction by hand, soon turned out to be tedious. 
So now she asks you to write a program that does the job for her! 

 

題意:輸入前序遍歷,中序遍歷,輸出後序遍歷。(看完之後如果不太理解可以看我下一篇隨筆,後續我會更新具體思考過程)

 

解題思路:1.首先需要根據前序遍歷和中序遍歷建立二叉樹

     我們這裡需要遞迴來實現,二叉樹問題和遞迴聯絡非常緊密。

      BitTree *createBinTreeByPreIn(char *pre,char *in,int number);

      函式需要三個引數:前序遍歷字串(*pre),和中序遍歷的字串(*in),字串個數(number)。

      結束條件:當字串長度為0時結束;

 

 1
BitTree *createBinTreeByPreIn(char *pre,char *in,int number) 2 { 3 if(number==0) return NULL; 4 char c = pre[0]; 5 int i = 0; 6 while(i<number && in[i]!=c)i++; 7 int leftNumber = i; 8 int rightNumber = number - i - 1; 9 BitTree *node = (BitTree *)malloc(sizeof
(BitTree)); 10 node->data = c; 11 node->lchild = createBinTreeByPreIn(&pre[1],&in[0],leftNumber); 12 node->rchild = createBinTreeByPreIn(&pre[leftNumber+1],&in[leftNumber+1],rightNumber); 13 return node; 14 }

 

     2.後續遍歷二叉樹

1 void PostOrder(BitTree *bt)
2 {
3     if(bt!=NULL)
4     {
5         PostOrder(bt->lchild);
6         PostOrder(bt->rchild);
7         printf("%c",bt->data);
8     }
9 }

最後加上主函式來測試我們的程式

 1 int main(int argc,char **argv)
 2 {
 3     char a[SIZE],b[SIZE];
 4     BitTree *p;
 5     while(scanf("%s%s",a,b)!=EOF)
 6     {
 7         p = createBinTreeByPreIn(a,b,strlen(a));
 8         PostOrder(p);
 9         printf("\n");
10     }
11     return 0;
12 }