华为机试练习150817第二题:求后序序列
来源:互联网 发布:下载网络缓存级别 编辑:程序博客网 时间:2024/05/16 15:54
import java.util.Scanner;/** * Created by cq on 2015/8/17 22:22. * 根据前序序列和中序序列,求后序序列,否则输出No * 这里没有对输入参数的合法性进行验证,因为合法性由机试系统保证 * 测试例: 8 1 2 4 7 3 5 6 8 4 7 2 1 5 3 8 6 8 1 2 4 7 3 5 6 8 4 1 2 7 5 3 8 6 8 1 2 4 5 3 6 7 8 4 5 2 1 6 3 9 7 * 结果: 7 4 2 5 8 6 3 1 No 5 4 2 6 9 7 3 1 */public class Main { public static void main(String[] args){ Scanner in = new Scanner(System.in); try { while (in.hasNextInt()){ int lenOfTree = in.nextInt(); int[] preorder = new int[lenOfTree], inorder = new int[lenOfTree]; for (int i=0; i<lenOfTree; i++){ preorder[i] = in.nextInt(); } for (int i=0; i<lenOfTree; i++){ inorder[i] = in.nextInt(); } String result = isBTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); if (result.indexOf("s") != -1){ result = "No"; } System.out.println(result); } }catch (Exception e){} finally { in.close(); } } public static String isBTree(int[] preorder, int pBegin, int pEnd, int[] inorder, int iBegin, int iEnd){ if (iBegin == iEnd){ return inorder[iBegin]+" "; } else if (iBegin > iEnd){ return ""; } int root = preorder[pBegin], indexOfRoot = indexOf(inorder, iBegin, iEnd, root); if (indexOfRoot == -1){ return "s"; } int leftLen = indexOfRoot-iBegin; return isBTree(preorder, pBegin+1, pBegin+leftLen, inorder, iBegin, indexOfRoot-1) + isBTree(preorder, pBegin+leftLen+1, pEnd, inorder, indexOfRoot+1, iEnd) +root+" "; } public static int indexOf(int[] arr, int froIndex, int endIndex, int target){ for (int i=froIndex; i<=endIndex; i++){ if (arr[i] == target){ return i; } } return -1; }}
0 0
- 华为机试练习150817第二题:求后序序列
- 华为机试练习2
- 华为机试第二篇
- 笔试系列-1-华为机试第二题
- 华为2014暑期实习生招聘机试第二题
- 华为机试练习150817第一题:名字的漂亮度
- 华为机试准备--练习(JAVA实现)
- 华为机试练习---划分数线
- 华为机试练习---求最小差值
- 华为机试练习---括号匹配问题
- 2015华为机试练习之合唱队
- 2014华为机试四川大学第二场
- 华为上机第二题
- 华为上机第二题
- 华为机试-DNA序列-C++
- 华为机试-C++--DNA序列
- 华为机试题练习总结
- 继续华为上机题练习
- java 多态理解
- webservice之简单创建和发布(一个加法运算)
- hdoj 2066 一个人的旅行
- 第三方(MBProgressHUD)
- SAS 补零
- 华为机试练习150817第二题:求后序序列
- SQL Server 与 Oracle数据类型映射
- Gold Coins POJ 2000
- win8右键无法新建文件
- oracle拆分逗号分隔字符串 实现split
- yum install与yum groupinstall区别
- 【InfoQ】TalkingData 肖文峰:移动大数据技术团队的高效敏捷进化之旅
- linux实用命令收集
- Win764位操作系统Oracle的问题