1. 程式人生 > >資料結構——已知先序中序求後序,已知中序後序求先序

資料結構——已知先序中序求後序,已知中序後序求先序

  總結下二叉樹的已知兩種遍歷方式求第三種遍歷順序的方法,已知先序和中序遍歷或者後序與中序遍歷後二叉樹是唯一確定的,下面介紹怎麼求出第三種遍歷順序。

  先序遍歷順序為:根結點——左子結點——右子結點,中序遍歷為:左子結點——根結點——右子結點,我們注意到,先序遍歷的第一個元素就是二叉樹根結點,我們在中序遍歷中以該元素分為左右兩部分,則左邊為左子樹,右邊為右子樹,遞迴即可還原二叉樹,這個過程中可直接輸出後序遍歷的順序。同理,可以用後序與中序還原出先序遍歷的順序。

程式碼及測試資料如下:

 1 #include <iostream>
 2 #include <cstdio>
 3
#include <cstring> 4 #include <algorithm> 5 #include <malloc.h> 6 #include <string> 7 #include <vector> 8 #include <stack> 9 #include <queue> 10 #include <set> 11 #include <map> 12 13 #define FRER() freopen("in.txt", "r", stdin); 14
15 using namespace std; 16 17 //函式狀態碼定義 18 #define TRUE 1 19 #define FALSE 0 20 #define OK 1 21 #define ERROR 0 22 #define INFEASIBLE -1 23 #define OVERFLOW -2 24 25 typedef char TElemType; 26 typedef int Status; 27 28 typedef struct BiNode { 29 TElemType data;
30 struct BiNode *lchild, *rchild; 31 }BiNode, *BiTree; 32 33 BiTree BinaryTreeFormorderings(char *, char *, int); 34 BiTree BinaryTreePostorderings(char *, char *, int); 35 36 /* 37 ABDECFG 38 DBEAFCG 39 DEBFGCA 40 */ 41 42 int main() 43 { 44 FRER() 45 int n; 46 char str[100], ptr[100]; 47 cin >> n >> str >> ptr; 48 BinaryTreePostorderings(str, ptr, n); 49 return 0; 50 } 51 52 BiTree BinaryTreeFormorderings(char *pre, char *in, int len) { 53 if(len <= 0) 54 return NULL; 55 BiNode *node = new BiNode; 56 node->data = *pre; 57 int idx = 0; 58 while(idx < len) { 59 if(*(in + idx) == *pre) 60 break; 61 ++idx; 62 } 63 node->lchild = BinaryTreeFormorderings(pre + 1, in, idx); 64 node->rchild = BinaryTreeFormorderings(pre + idx + 1, in + idx + 1, len - (idx + 1)); 65 cout << node->data << ' '; 66 return node; 67 } 68 69 BiTree BinaryTreePostorderings(char *in, char *post, int len) { 70 if(len == 0) 71 return NULL; 72 BiNode *node = new BiNode; 73 node->data = *(post + len - 1); 74 cout << node->data << ' '; 75 int idx = 0; 76 while(idx < len) { 77 if(*(in + idx) == *(post + len - 1)) 78 break; 79 ++idx; 80 } 81 node->lchild = BinaryTreePostorderings(in, post, idx); 82 node->rchild = BinaryTreePostorderings(in + idx + 1, post + idx, len - (idx + 1)); 83 return node; 84 }