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

2022-03-03 15:49:36 字數 1781 閱讀 4324

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

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

**及測試資料如下:

1 #include 2 #include 3 #include 4 #include 5 #include 

6 #include

7 #include 8 #include 9 #include 10 #include

11 #include 12

13#define frer() freopen("in.txt", "r", stdin);

1415

using

namespace

std;

1617

//函式狀態碼定義

18#define true 1

19#define false 0

20#define ok 1

21#define error 0

22#define infeasible -1

23#define overflow -2

2425 typedef char

telemtype;

26 typedef int

status;

2728 typedef struct

binode binode, *bitree;

3233 bitree binarytreeformorderings(char *, char *, int

);34 bitree binarytreepostorderings(char *, char *, int

);35

36/*

37abdecfg

38dbeafcg

39debfgca

40*/

4142

intmain()

4351

52 bitree binarytreeformorderings(char *pre, char *in, int

len)

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 << '';

66return

node;67}

6869 bitree binarytreepostorderings(char *in, char *post, int

len)

81 node->lchild = binarytreepostorderings(in

, post, idx);

82 node->rchild = binarytreepostorderings(in + idx + 1, post + idx, len - (idx + 1

));83

return

node;

84 }

已知後序中序,求先序

利用後序遍歷的最後乙個元素 根結點 在中序遍歷中找到它,分割為左子樹和右子樹,然後在後序遍歷中找到子樹的根結點 起點 終點,分別遞迴。int leftrootpo rootpo end rootin 1 左子樹的根結點在後序遍歷中的位置。end rootin 右子樹的結點個數 int leftsta...

已知中序和後序求先序

include include using namespace std struct tnode define len sizeof tnode typedef tnode pbtnodepoint void vcreate string sinorder,string spostorder,pbt...

已知後序跟中序求先序

分類 資料結構 2013 11 28 19 52 7人閱讀收藏 舉報而已知後序遍歷和中序遍歷求前序遍歷的過程差不多,但由於後序遍歷是最後才訪問根節點的 所以要從後開始搜尋,例如上面的例子,後序遍歷為 gbdehfca,中序遍歷為 dgbaechf 後序遍歷中的最後乙個元素是根節點,a,然後查詢中序中...