(學堂線上OJ)真二叉樹重構(Proper Rebuild)
題目位址:https://dsa.cs.tsinghua.edu.cn/oj/problem.shtml?id=1146
思路:二叉樹可沿左側邊分解為 左側節點+其右子樹 的形式(以下簡稱L-R子樹),此時,中序周遊可表示為如下形式:
通過前序周遊可以輕松得到L,接下來确定其對應R子樹的前序及後序周遊序列(标注在全樹序列上的位置即可),将得到的L-R子樹塊存入棧中,再沿左側下行,直至最左側節點。
如上圖所示,中序周遊起始于最左側節點,即此時的棧頂,彈出并輸出棧頂後,然後将控制權交給其R子樹。
下一個待輸出的節點亦為該子樹中序周遊的起點,如此反複疊代。
R子樹處理完後,控制權将上交給上一級L,與中序周遊順序一緻。
下面代碼的核心函數getTopRTree作用:彈出棧頂L,分析其R子樹并以 “L-R子樹模式” 存入。
反複調用該函數直至棧為空即可。
#pragma warning(disable : 4996)
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXSIZE = 4000000;
struct RTree {//L-R子樹模式(後四項全為-1表示無R子樹)
int head, preF, preL, postF, postL;
};
RTree stack[MAXSIZE / 2];//RTree棧
int pre[MAXSIZE];//全樹前序周遊序列
int post[MAXSIZE];//全樹後序周遊序列
int top = -1;//RTree棧棧頂
int search(int* arr, int F, int L, int value);//在arr數組中定位值為value的字元
int getTopRTree();
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i)//全樹前序周遊序列
scanf("%d", &pre[i]);
for (int i = n - 1; -1 < i; --i)//全樹後序周遊序列
scanf("%d", &post[i]);
stack[++top] = { 0, 0, n, 0, n };//建立一個以全樹為R子樹的L-R子樹塊
getTopRTree();//進而用全樹初始化棧
while (-1 < top)
printf("%d ", getTopRTree());
return 0;
}
int getTopRTree() {//彈出L,分析其R子樹并以“L-R子樹模式”存入
if (-1 == stack[top].preF) return stack[top--].head;//無右子樹,直接pop
int head = stack[top].head;
int preF = stack[top].preF, preL = stack[top].preL, postF = stack[top].postF, postL = stack[top].postL;
--top;//pop
while (true) {//沿左側下行,以“L-R子樹模式”将此樹壓入棧中
if (preL - preF < 2) {//無左右子樹
stack[++top] = { pre[preF], -1, -1, -1, -1 };//push
break;
break;
}
stack[++top] = { pre[preF],search(pre,preF,preL,post[postF + 1]),preL,postF + 1,search(post,postF,postL,pre[preF + 1]) };//push
break;
++preF;//下行
preL = stack[top].preF;
postF = stack[top].postL;
}
return head;//傳回被彈出的L
}
int search(int* arr, int F, int L, int value) {//在arr數組中定位值為value的字元
while (arr[F] != value) ++F;
return F;
}