[cpp]view plain
copy
#include
using
namespace
std;
#define treelen 6
//資料結構定義
struct
node
; void
rebuild(
char
* ppreorder,
char
* pinorder,
intntreelen,node** proot)
//獲得前序遍歷的第乙個節點
node* ptemp = new
node;
ptemp->chvalue = *ppreorder;
ptemp->pleft = null;
ptemp->pright = null;
//如果節點為空,把當前節點複製到根節點
if(*proot == null)
//如果當前樹長度為1,那麼已經是最後乙個節點
if(ntreelen == 1)
//尋找子樹長度
char
* porginorder = pinorder;
char
* pleftend = pinorder;
intntemplen = 0;
//找到左子樹的結尾
while
(*ppreorder != *pleftend)
ntemplen++;
//記錄臨時長度,以免溢位
if(ntemplen > ntreelen)
pleftend++;
} //尋找左子樹長度
intnleftlen = 0;
nleftlen = (int
)(pleftend-porginorder);
//尋找右子樹長度
intnrightlen = 0;
nrightlen = ntreelen - nleftlen - 1;
//重建左子樹
if(nleftlen > 0)
//重建右子樹
if(nrightlen > 0)
} //前序遍歷結果
void
preprint(node* proot)
cout; preprint(proot->pleft);
preprint(proot->pright);
} //中序遍歷結果
void
inprint(node* proot)
inprint(proot->pleft);
cout; inprint(proot->pright);
} void
main()
; char
szinorder[treelen] = ;
node* proot = null;
rebuild(szpreorder,szinorder,treelen,&proot);
preprint(proot);
cout<
inprint(proot);
cout<}
/*a b d c e f
d b a e c f*/
已知前序遍歷和中序遍歷求二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請輸出後序遍歷序列。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,重建二叉樹並返回後序遍歷序列 輸入某二叉樹的前序遍歷和中序遍歷的結果 輸出後序遍歷序列 1 2 4 7 3 5 6 8 4 7 2 1 5 3 8 6...
已知前序和中序遍歷,重建二叉樹
想在牛客網上寫此題目,此處 題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。分析 前序遍歷 根節點 左子樹 右子樹 中序遍歷 左子樹 根節點 右子樹 後序遍歷 左子樹 右...
二叉樹 已知前序遍歷和中序遍歷,輸出後續遍歷
已知某二叉樹的先序序列和中序序列,程式設計計算並輸出該二叉樹的後序序列。輸入說明 僅一組資料,分為兩行輸入,第一行表示指定二叉樹的先序序列,第二行表示該二叉樹的中序序列,序列元素均為大寫英文本元,表示二叉樹的結點。輸出說明 在一行上輸出該二叉樹的後序序列。輸入樣本 abdgcefh dgbaechf...