Given two depth-first-search (DFS) sequences of a binary tree, can you find a binary tree which satisfies both of the DFS sequences?
Recall that a binary tree is a tree in which each vertex has at most two children, and the depth-first search is a tree traversing method which starts at the root and explores as far as possible along each branch before backtracking.
给定二组序列,分别为同一个二叉树的 DFS 序列(序列不同在于对于有两个子节点 x, y 的父节点 p ,DFS 按随机选择优先访问 x 或 y )。
解题思路
对 DFS 结果序列进行模拟,可以类似的参考树的前、中、后序互相转换的递归思路。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 100000 + 10;
int a[N], b[N]; //序列 A, B
int posa[N], posb[N]; // 节点值 i 在序列 A(B) 中的位置
int pa[N]; // 记录节点值 i 的父节点值
int p; // p-1 表示当前已知道了多少个节点的父节点 -> 即 p 为之后需处理第 p 个点的父节点
void solve(int pos,int l,int r,int fa){ //当前需处理 A[pos] 的父节点,对应 B 序列的区间为 [l,r]
if(l>r) return;
if(a[pos]==b[l]){
pa[a[pos]]=fa;
p++;
solve(pos+1,l+1,r,a[pos]);
if(p-pos<=r-l){
int tmp=p;
pa[a[tmp]]=fa;
p++;
solve(tmp+1,l+tmp-pos+1,r,a[tmp]);
}
}
else{
pa[a[pos]]=fa;
p++;
int len1=posa[b[l]]-pos-1;
solve(pos+1,posb[a[pos]]+1,posb[a[pos]]+len1,a[pos]);
pa[b[l]]=fa;
p++;
solve(posa[b[l]]+1,l+1,posb[a[pos]]-1,b[l]);
}
}
int main()
{
int T,n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<=n;++i)
scanf("%d",&a[i]), posa[a[i]]=i;
for(int i=1;i<=n;++i)
scanf("%d",&b[i]), posb[b[i]]=i;
p=1;
solve(1,1,n,0);
for(int i=1;i<=n;++i){
if(i>1) printf(" ");
printf("%d",pa[i]);
}
printf("\n");
}
}