若給出二叉樹的前序和中序,或者給出二叉樹的後序和中序,可以還原出唯一的二叉樹。但給出前序和後序不可以。
1.前序和中序
遞迴演算法
根據二叉樹的前序序列和中序序列,還原二叉樹。分析可知,前序序列的第乙個元素是該二叉樹的根結點,在中序序列中找到根結點的位置(下標),便可知道該二叉樹的左右子樹中各自結點的個數。據此,可將前序序列分為:根結點+左子樹+右子樹,將中序序列分為:左子樹+根結點+右子樹。問題又轉化為,根據左右子樹的前序序列和中序序列,分別還原二叉樹(左右子樹)。
/*根據二叉樹的前序和中序還原二叉樹,遞迴演算法,函式返回根結點*/
//設前序序列preorder[n+1],中序序列inorder[n+1],下標均為[1,n]
bitnode *
creat_tree
(int pre_l,
int pre_r,
int in_l,
int in_r)
//建立根結點
bitnode *t=
(bitnode *
)malloc
(sizeof
(bitnode));
t->data=preorder[pre_l]
;//還原左右子樹
t->lchild=
creat_tree
(pre_l+
1,pre_l+pos-in+l,in_l,pos-1)
; t->rchild=
creat_tree
(pre_r-in_r+pos+
1,pre_r,pos+
1,in_r)
;//函式返回根結點
return t;
}
2.後序和中序
遞迴演算法
同理
/*根據二叉樹的後序和中序還原二叉樹,遞迴演算法,函式返回根結點*/
//設後序序列postorder[n+1],中序序列inorder[n+1],下標均為[1,n]
bitnode *
creat_tree
(int post_l,
int post_r,
int in_l,
int in_r)
//建立根結點
bitnode *t=
(bitnode *
)malloc
(sizeof
(bitnode));
t->data=postorder[post_r]
;//還原左右子樹
t->lchild=
creat_tree
(post_l,post_l+k-in_l-
1,in_l,k-1)
; t->rchild=
creat_tree
(post_l+k-in_l,post_r-
1,k+
1,in_r)
;//函式返回根結點
return t;
}
非遞迴演算法/*根據二叉樹的後序和中序還原二叉樹,非遞迴演算法*/
#include
//使用二叉樹的順序儲存結構,二叉樹所有結點儲存在sqtree陣列裡
int sqtree[
2001]=
int index_in[
2001]=
;//儲存對應結點i在中序序列inorder中的下標
int n;
//結點總數
/*該函式將後序序列postorder中,從最後乙個結點到第乙個節點,乙個個放入sqtree中*/
intput_root
(int root,
int inorder,
int postorder)
;int
main()
//輸入後序序列,下標[1,n]
for(
int i =
1; i <=n; i++
)scanf
("%d"
,&postorder[i]);
//輸入中序序列,下標[1,n]
for(
int i =
1; i <=n; i++
)scanf
("%d"
,&inorder[i]);
sqtree[1]
=postorder[n]
;//根結點為後序序列最後乙個元素
for(
int i=
1;i<=n;i++
)//找到根結點在中序序列中的下標,存入index_in[1]
if(inorder[i]
==sqtree[1]
)//還原二叉樹
for(
int i=n-
1;i>=
1;i--
)//按照層序輸出二叉樹
for(
int i=
0;i(sqtree[i]!=0
)//0為不存在該結點
printf
("%d "
,sqtree[i]);
printf
("%d"
,sqtree[result]);
return0;
}/*該函式將後序序列postorder中,從最後乙個結點到第乙個節點,乙個個放入sqtree中*/
intput_root
(int root,
int inorder,
int postorder)
while
(sqtree[i]!=0
) index_in[i]
=j;sqtree[i]
=inorder[j]
;return i;
}
二叉樹 還原二叉樹 二叉搜尋樹
先序遍歷的特點 先遍歷根結點,再遍歷左子樹,最後再遍歷右子樹 中序遍歷的特點 先遍歷左子樹,再遍歷根結點,最後再遍歷右子樹 後序遍歷的特點 先遍歷左子樹,再遍歷右子樹,最後再遍歷根結點 舉例 先序遍歷 a b d f g h i e c 中序遍歷 f d h g i b e a c 如上,根據先序遍...
還原二叉樹
給定一棵二叉樹的先序遍歷序列和中序遍歷序列,要求計算該二叉樹的高度。輸入資料有多組,每組資料第一行輸入 1個正整數 n 1 n 50 為樹中結點總數,隨後 2行先後給出先序和中序遍歷序列,均是長度為 n的不包含重複英文本母 區分大小寫 的字串。輸出乙個整數,即該二叉樹的高度。9 abdfghiec ...
還原二叉樹
資料結構實驗之二叉樹四 還原二叉樹 time limit 1000ms memory limit 65536k 有疑問?點這裡 題目描述 給定一棵二叉樹的先序遍歷序列和中序遍歷序列,要求計算該二叉樹的高度。輸入輸入資料有多組,每組資料第一行輸入1個正整數n 1 n 50 為樹中結點總數,隨後2行先後...