ZOJ 3965 Binary Tree Restoring (递归)

2 篇文章 0 订阅

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");
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值