(学堂在线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;
}