华为机试练习150817第二题:求后序序列
2015-08-18 09:20
471 查看
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; } }
相关文章推荐
- UILabel自动换行适应
- 杭电2112HDU Today(map 最短路径)
- 设计模式之Builder
- Error -27728: Step download timeout (120 seconds)的解决方法
- 洛谷1017 进制转换
- TCP三次握手注意事项
- 算法竞赛入门经典:第七章 暴力求解法 7.7解答树
- 批量修改文件权限
- Java修饰符关键词
- httpwebRequest大文件上传
- 08-17工作总结
- 内部类详解
- 【问题解决】使用Strust2文件上传图片无法显示
- php学习-15超全局变量
- 进程和线程的区别与联系
- HashCode与equal 的作用与区别
- hadoop2.0的datanode数据存储文件夹策略的多个副本
- 4、OLCD程序
- Android的屏幕适配总结
- Utils