先序中序轉二叉樹

2021-10-07 07:23:05 字數 1496 閱讀 7220

在紙上計算一下他們轉的過程就很容易發現規律

寫程式更簡單,只需要計算出每個子樹的起始位置

計算的時候使用靜態鍊錶更為方便

#include

#include

#include

#include

#include

using

namespace std;

struct node

;vector<

int> in, pre;

vector t;

map<

int,

int> mp;

// 靜態指標

int p =-1

;// 由先序、中序建立

intbuild

(int inl,

int inr,

int prel,

int prer)

// 後序

void

dfs(

int k)

if(t[k]

.right !=-1

) cout << t[k]

.data<<

' ';

}// 層次

void

bfs()}

intmain()

for(

int i =

0; i < n; i++

)build(0

, n -1,

0, n -1)

;// bfs();

// dfs(0);

return0;

}

#include

#include

#include

#include

#include

using

namespace std;

struct node

;vector<

int> in, post;

vector t;

map<

int,

int> mp;

// 靜態指標

int p =-1

;// 由先序、中序建立

intbuild

(int inl,

int inr,

int postl,

int postr)

// 先序

void

dfs(

int k)

if(t[k]

.right !=-1

)}// 層次

void

bfs()}

intmain()

for(

int i =

0; i < n; i++

)build(0

, n -1,

0, n -1)

;// bfs();

dfs(0)

;return0;

}

二叉樹中序先序轉後序

如圖,此二叉樹 先序遍歷為426315 中序遍歷為623415 求後序遍歷結果 步驟 426315 623415 4為根節點,則中序分為62315 左子樹623的跟為先序6315的2 則6和3為2的左兒子和右兒子。發現一直重複這一過程,則實行遞迴程序 函式解析 prein2post preorder...

先序中序重建二叉樹

includeusing namespace std vectorpre,in int p typedef struct node vectorpost int rec int l,int r 通過前序和後序得到樹 int main for int i 0 i tem in.push back te...

二叉樹 先序 中序 後序

同學整理的,順便傳上分享下 一,已知先序和中序 求後序 1 include2 include3 include4 using namespace std 5char s1 10 s2 10 ans 10 6 int o 0 7 void tree int n char s1 char s2 char...