題目:設一棵滿二叉樹(所有節點值均不相同),已知其先序序列爲pre,設計一個算法求其後序序列post.
Pre : N L R
l1, l1+1,l1+half, l1+half+1,h1
Post: L R N
L2,L2+half-1 L2+half,h2-1 h2
算法思想:對於滿二叉樹,任意一個節點的左右子樹均含有相等的結點數,同時,先序序列的第一個節點作爲後序序列的最後一個節點。遞歸模型如下:
F(pre,L1,h1, post,L2,h2) :不做任何事情 當h1<L1
F(pre,L1,h1, post,L2,h2):post(h2)=pre(L1)
取中間位置half=(h1-L1)/2;
將f(pre,l1+1,l1+half)先序序列左子樹轉換爲post(L2,L2+half-1),
將f(pre,l1+half+1,h1)先序序列右子樹轉換爲post(L2+half,h2-1),
[注] post(h2)=pre(L1) 使先序序列的第一個節點等於後序遍歷的最後一個節點
在這裏插入代碼片
Void PreToPost( elemtype pre[],int L1,int h1,elemtype post[],int L2, int h2,){
If(L1<h1) return; //合法性判斷:不作操作
If(h1>L1){
Post[h2]=pre[L1]; //遞歸出口:將先序序列第一個節點作爲後序序列最後一個
Int half=(h1-L1)/2; // 取先序序列一半長度
PreToPost( elemtype pre[],int l1+1,int l1+half, elemtype post[],int L2, intL2+half-1)
//將先序序列左子樹轉化爲後序序列左子樹
PreToPost( elemtype pre[],int l1+half+1,int h1, elemtype post[],int L2+half, int h2-1)
//將先序序列右子樹轉化爲後序序列右子樹
}
}