二叉树(Tree Recovery)

2023-05-16

Tree Recovery
Time Limit:3000MS Memory Limit:Unknown 64bit IO Format:%lld & %llu

Submit  Status

Description

Download as PDF

Little Valentine liked playing with binary trees very much. Her favorite game was constructing randomly looking binary trees with capital letters in the nodes.

This is an example of one of her creations:


                                    D
                                   / \
                                  /   \
                                 B     E
                                / \     \
                               /   \     \ 
                              A     C     G
                                         /
                                        /
                                       F
  

To record her trees for future generations, she wrote down two strings for each tree: a preorder traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree).

For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG.

She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried it).


Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed possible, but only because she never had used the same letter twice in the same tree.

However, doing the reconstruction by hand, soon turned out to be tedious.

So now she asks you to write a program that does the job for her!

Input Specification 

The input file will contain one or more test cases. Each test case consists of one line containing two strings preord and inord, representing the preorder traversal and inorder traversal of a binary tree. Both strings consist of unique capital letters. (Thus they are not longer than 26 characters.)

Input is terminated by end of file.

Output Specification 

For each test case, recover Valentine's binary tree and print one line containing the tree's postorder traversal (left subtree, right subtree, root).

Sample Input 


DBACEGF ABCDEFG
BCAD CBAD
  

Sample Output 


ACBFGED
CDAB
  
【分析】

       根据先序遍历确定二叉树的根root,再由根root根据中序遍历,确定左右子树,根据root在先序遍历与中序遍历中的位置,划分出左右子树的范围。这样又出现了两棵树,同时我们还具有这两棵的先序遍历和中序遍历。使用递归建树,已知树后,对树进行后序遍历得到结果。

       创建数组 lch 和 rch ,数组的下标为结点,数组的元素是结点所对应的左结点和右结点(的下标)。可以利用这两个数组进行建树。我们只要已知整棵树的根的下标,就可以通过下标,得知左右结点的值,依次得出各个结点的值(在遍历过程中)。

用java语言编写程序,代码如下:

import java.io.BufferedInputStream;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(new BufferedInputStream(System.in));
		final int maxn = 1000 + 5;
		while(input.hasNext()) {
			char[] preorder = input.next().toCharArray();
			char[] inorder = input.next().toCharArray();
			int n = preorder.length;
			
			int[] lch = new int[maxn];//左结点
			int[] rch = new int[maxn];//右结点
			build(0, n - 1, 0, n - 1, preorder, inorder, lch, rch);//建立二叉树
			post_traversal(preorder[0], lch, rch);//后序遍历
			System.out.println();
		}
	}
	
	//把preorder[l1...r1]和inorder[l2...r2]建成一棵二叉树,返回树根
	public static int build(int l1, int r1, int l2, int r2, 
			char[] preorder, char[] inorder, int[] lch, int[] rch) {
		if(l2 > r2) return 0;//空树
		int root = preorder[l1];
		int p = l2;
		while(inorder[p] != root) p++;
		int cnt = p - l2;//左子树的结点个数
		lch[root] = build(l1 + 1, l1 + cnt, l2, p - 1, preorder, inorder, lch, rch);
		rch[root] = build(l1 + cnt + 1, r1, p + 1, r2, preorder, inorder, lch, rch);
		//System.out.println(root);
		return root;
	}
	
	public static void post_traversal(char root, int[] lch, int[] rch) {
		if(root >= 'A' && root <= 'Z') {
			post_traversal((char) lch[root], lch, rch);
			post_traversal((char) rch[root], lch, rch);
			System.out.print(root);			
		}
	}
	
	
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

二叉树(Tree Recovery) 的相关文章

  • 如何使用 php 列出目录以在文件夹中导航,而不使用 javascript? [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我正在寻找这个 PHP 函数 列出目
  • 基本树概念:定义祖先

    祖先的定义是什么 更具体地说 E 会是 H 的祖先吗 或者更简单地说 F C A 是 H 的祖先 也许甚至是G 我只是想澄清这个简单的概念 E 不是 H 的祖先 它是uncle因为它是一个siblingF 的parent of H F C
  • 创建二叉树的时间复杂度

    我正在尝试从提供的源创建一棵树 要添加到树中的 2 个节点 以及应添加这 2 个新闻节点的节点 为了找到该节点在树中的位置 我使用了中序遍历 该遍历的时间复杂度为 O n 因此 如果要在树中添加 n 个节点 则创建整个树的时间复杂度为 O
  • 二叉搜索树是平衡的吗?

    这已经讨论过了here https stackoverflow com questions 742844 how to determine if binary tree is balanced 但我在下面有一个实现 线程中从未讨论过 pub
  • 为什么在算法中使用子树大小来选择二叉树中的随机节点?

    我偶然发现了从二叉树中选择随机节点的算法的几种实现 它们都使用子树大小属性 但是 我不明白为什么知道子树大小有帮助 这是实现A https stackoverflow com a 32011526 and B https www geeks
  • Beaglebone Black 上的 GPIO

    我目前遇到了 Beaglebone black GPIO 引脚的问题 我正在寻找一种正确的方法来读取 C 中的 GPIO 引脚 p8 4 的值 如果我理解正确的话 我尝试使用一个库 该库使用了在引入设备树之前不支持的旧方法 我尝试寻找其他解
  • 绘制java类的依赖关系图

    嘿嘿 我正在寻找像 JDepend 这样的工具来为 java 类文件绘制图表 JDepend 看起来很好 但它没有从 deps 中解析 deps 也许我只是缺少一些特殊选项 直接输出为 dot 格式或图像会很好 谢谢 你可以试试Java依赖
  • Elasticsearch 崩溃后无法恢复

    磁盘空间不足 导致 Elasticsearch 分片崩溃 三个节点现在为红色 两个节点已恢复 它们的状态为黄色 ES 的 CPU 利用率为 150 内存利用率很高 正在尝试恢复它们 但似乎存在一些版本匹配冲突 我清理了磁盘空间并删除了分片的
  • 如何按层次结构对文件路径名进行排序?

    我想按层次结构对文件名进行排序 假设我有以下文件夹列表 D Movies Hollywood Comedy adultcomedy D Movies Hollywood Comedy horrorcomedy D Movies Hollyw
  • 用 pandas 查找树中叶节点的所有祖先

    我有一个表 有两列 父 和 子 这是从 SAP ERP 下载的 SETNODE 表 需要在 python 中创建一个数据框 其中每个级别作为其自己的列 相对于其父级和之前的所有级别 在Python 3 中 完整关系的级别数量未知 或始终变化
  • 在 Python 中删除表达式树及其每个子表达式树中第一个元素周围的括号

    目标是实现简化操作 删除表达式树及其每个子表达式树中第一个元素周围的括号 其中表达式作为括在各个括号中的字符串输入给出 这必须适用于任意数量的括号 例如 12 3 45 6 gt 123 45 6 删除 12 周围的括号 然后删除 45 周
  • java数据结构模拟数据树

    我需要帮助定义使用什么方法 我有一个 SOAP 响应 给我一个 xml 文件 我需要在屏幕上显示 3 个相关列表 当您在第一个列表中选择一个项目时 相应的选择将出现在第二个列表中 依此类推 我只对从 xml 流中提取数据后如何有效地组织数据
  • 在关系数据库中存储树结构的已知方法有哪些? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 使用 Java 进行树可视化 [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在寻找一个库来生成图形或树 例如组织图表 该库应该能够从该图中生成纯图像 有谁知道一个好的 希望开源
  • 如何从 Trie 中检索给定长度的随机单词

    我有一个简单的 Trie 用来存储大约 80k 长度为 2 15 的单词 它非常适合检查字符串是否是单词 但是 现在我需要一种获取给定长度的随机单词的方法 换句话说 我需要 getRandomWord 5 来返回 5 个字母的单词 所有 5
  • 为什么Aries在数据库管理恢复中要先执行redo before undo?

    如果 Aries 算法已经知道在分析阶段之后要撤消哪些事务 为什么它会在撤消之前应用重做 我知道 认为 这与 Lsn 数字和维护一致性有关 因为在磁盘上刷新的数据撤消事务可能与崩溃时撤消事务不同 由于脏数据 页 但我找不到这个问题的任何 正
  • 如何从此 d3.js layout.tree 获取树祖先和树后代的列表?

    我正在尝试和修改this https bl ocks org mbostock 4339083d3 js 的示例 用于根据 JSON 树结构绘制树 这就是树的一部分开始时的样子 我正在尝试进行两个单独的修改 但我不知道该怎么做 当单击节点的
  • 如何在 Twig 中渲染树

    我想渲染一棵深度不确定的树 孩子的孩子的孩子等 我需要递归地循环遍历数组 我怎样才能在 Twig 中做到这一点 我玩过domi27的想法 https stackoverflow com questions 8326482 how to re
  • ExtJs4 Json TreeStore?

    我正在将 ExtJs3 应用程序迁移到 ExtJs4 在 ExtJs3 中 我有一个树网格 它有一个加载器来加载树数据 如下所示 loader new Ext tree TreeLoader dataUrl Department Depar
  • XSLT 将平面树结构转换为列表

    我有一个描述eshop树结构的xml文件 我只需要获取所有子组的列表 我不知道结构中有多少个父 子级别 输入 xml 如下所示

随机推荐

  • 代码对齐(Alignment of Code)

    Alignment of Code Time Limit 4000 2000 MS Java Others Memory Limit 32768 32768 K Java Others Total Submission s 958 Acce
  • Ducci序列(Ducci Sequence)

    Ducci Sequence Time limit 3 000 seconds A Ducci sequence is a sequence of n tuples of integers Given an n tuple of integ
  • 卡片游戏(Throwing cards away I)

    Problem B Throwing cards away I Given is an ordered deck of n cards numbered 1 to n with card 1 at the top and card n at
  • 交换学生(Foreign Exchange)

    Problem E Foreign Exchange Input standard input Output standard output Time Limit 1 second Your non profit organization
  • CAN通信物理容错测试checklist

    CAN通信物理容错测试checklist 工作项目中 xff0c 我们有时有些产品CAN总线功能 xff0c 一般情况下我们必须要满足以下几种状况的测试项才算符合要求 一 CAN H与CAN L短路 判定标准 xff1a 短接故障发生后 x
  • 对称轴(Symmetry)

    Symmetry Time limit 3 000 seconds The figure shown on the left is left right symmetric as it is possible to fold the she
  • 打印队列(Printer Queue)

    Printer Queue Time limit 3 000 seconds 分析 首先记录所求时间它在队列中的位置 xff0c 用一个队列存储这些任务的优先级 xff0c 同时也创建一个队列存储对应任务一开始的位置 xff0c 那么当我们
  • 更新字典(Updating a Dictionary)

    Updating a Dictionary Time Limit 1000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description In th
  • 铁轨(Rails)

    Rails Time limit 3 000 seconds Rails There is a famous railway station in PopPush City Country there is incredibly hilly
  • 矩阵链乘(Matrix Chain Multiplication)

    Matrix Chain Multiplication Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description
  • 天平(Not so Mobile)

    Not so Mobile Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Before being
  • 下落的树叶(The Falling Leaves)

    The Falling Leaves Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Each yea
  • 四分树(Quadtrees)

    Quadtrees Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description A quadtree is a r
  • 油田(Oil Deposits)

    Oil Deposits Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description The GeoSurvCom
  • Abbott的复仇(Abbott's Revenge)

    Abbott 39 s Revenge Time limit 3 000 seconds Abbott s Revenge Abbott s Revenge The 1999 World FinalsContest included a p
  • rockchip rk3568 openwrt修改根文件系统分区

    rk3568的openwrt根文件系统分区大小如何修改 xff1f 1 rootfs大小取决于rk356x config的配置 xff0c 默认CONFIG TARGET ROOTFS PARTSIZE 61 512 xff0c 如果需要修
  • 除法(Division)

    Division Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Write a program th
  • 最大乘积(Maximum Product)

    Maximum Product Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Problem D M
  • 分数拆分(Fractions Again?!)

    Fractions Again Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Problem A F
  • 二叉树(Tree Recovery)

    Tree Recovery Time Limit 3000MS Memory Limit Unknown 64bit IO Format lld amp llu Submit Status Description Little Valent