由二叉樹的前序和中序如何獲得二叉樹的後序呢?要給出答案,首先得明白什麼是前序、中序、後序。node
二叉樹前序:遍歷順序爲,根節點、左子樹、右子樹;中序:遍歷順序爲,左子樹、根節點、右子樹;後序:遍歷順序爲,左子樹、右子樹、根節點post
能夠發現,二叉樹前序中的第一個節點爲樹的根節點root,而後找出root在中序裏面的位置,就能夠把前序和中序分別劃分爲左、右子樹兩個部分,而後遞歸調用便可。spa
舉個例子,前序 5 3 2 4 8 6 10 中序 2 3 4 5 6 8 103d
首先,5確定是二叉樹的根節點,而後5在中序裏面的位置是3號(從0開始),此位置前面的是左子樹中的節點,右面的是右子樹的節點,即5 || 3 2 4 || 8 2 6 , 2 3 4 || 5 || 6 8 10,對紅色的左子樹序列、藍色的右子樹序列繼續上述過程,直至結束。code
由後序和中序求前序也是像相似的思想。可是僅僅知道前序和後序沒法肯定二叉的形狀。好比前序 1 2 3 後序 3 2 1 則下面兩種狀況都符合blog
附二叉樹前序和中序生成後序的代碼遞歸
1 //二叉樹 前序和中序獲得後序 2 #include <stdio.h> 3 typedef struct node 4 { 5 int key; 6 struct node *left; 7 struct node *right; 8 }treeNode; 9 10 int pre_order[100]; 11 int mid_order[100]; 12 13 treeNode* construct_post_order(int pre_l, int pre_r, int mid_l, int mid_r) 14 { 15 if (pre_r - pre_l < 0) 16 { 17 return NULL; 18 } 19 treeNode *root; 20 root = new treeNode; 21 root->key = pre_order[pre_l]; 22 if (pre_r == pre_l) 23 { 24 root->left = NULL; 25 root->right = NULL; 26 return root; 27 } 28 int index; 29 for (index = mid_l; index <= mid_r; index++) 30 { 31 if (mid_order[index] == pre_order[pre_l]) 32 break; 33 } 34 root->left = construct_post_order(pre_l+1, pre_l+(index-mid_l), mid_l, index-1); 35 root->right = construct_post_order(pre_l+(index-mid_l)+1, pre_r, index+1, mid_r); 36 return root; 37 } 38 39 void post_Order(treeNode *root) 40 { 41 if(root != NULL) 42 { 43 post_Order(root->left); 44 post_Order(root->right); 45 printf("%d ", root->key); 46 } 47 } 48 49 int main() 50 { 51 int n; 52 printf("輸入序列的長度\n"); 53 scanf("%d", &n); 54 printf("輸入二叉樹前序\n"); 55 for (int i = 0; i < n; i++) 56 scanf("%d", &pre_order[i]); 57 printf("輸入二叉樹中序\n"); 58 for (int i = 0; i < n; i++) 59 scanf("%d", &mid_order[i]); 60 treeNode *root = construct_post_order(0, n-1, 0, n-1); 61 printf("二叉樹的後序爲\n"); 62 post_Order(root); 63 printf("\n"); 64 scanf("%d", &n); 65 66 return 0; 67 }