ZOJ 3965 Binary Tree Restoring (递归)
来源:互联网 发布:java模拟器 编辑:程序博客网 时间:2024/04/26 08:25
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, Bint 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"); }}
0 0
- ZOJ 3965 Binary Tree Restoring (递归)
- zoj 3965 Binary Tree Restoring(* dfs)
- HDU 1710 Binary Tree Traversals(递归)
- Invert Binary Tree 递归
- [agc005c]Tree Restoring
- 树和递归(一)[leetcode]Balanced Binary Tree
- 104. Maximum Depth of Binary Tree(递归)
- LeetCode:Binary Tree Traversal(二叉树遍历非递归)
- LeetCode 563 Binary Tree Tilt(递归 + 中间结果保存)
- 二叉排序树(Binary Sort Tree)的查找递归算法
- 【Leetcode】144. Binary Tree Preorder Traversal 【Tree】【递归&&非递归】
- 【启发】94. Binary Tree Inorder Traversal(树的非递归遍历 + 栈模拟递归)
- ****(leetcode) Binary Tree Postorder Traversal (tree后序遍历非递归实现)
- [LeetCode] Binary Tree Preorder Traversal [递归版]
- [LeetCode] Binary Tree Inorder Traversal [递归版]
- [LeetCode] Binary Tree Postorder Traversal [递归版]
- 递归-----Search Range in Binary Search Tree
- LeetCode 110. Balanced Binary Tree 递归求解
- SQLITE3 使用总结(五)
- POJ
- Linux ALSA声卡驱动之一:ALSA架构简介
- Eclipse(JavaIDE,javaEE,C++,PHP)图片教程四合一
- VC6.0双缓冲绘图和自绘控件
- ZOJ 3965 Binary Tree Restoring (递归)
- SecureCRT连接虚拟机中的Linux系统(Ubuntu)
- vsftp被动模式启用iptables访问设置
- LTE issue 3
- 深度学习存在的问题及解决方法
- oj20. Valid Parentheses
- WireShark技巧、Android OOM案例分析
- spring的测试
- SQLITE3 使用总结(六)