zoukankan      html  css  js  c++  java
  • 华为机试练习150817第二题:求后序序列


    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;
        }
    }
    
  • 相关阅读:
    hcharts实现堆叠柱形图
    程序员常用的六大技术博客类
    程序员常用的六大技术博客类
    程序员常用的六大技术博客类
    程序员常用的六大技术博客类
    前端几个常用简单的开发手册拿走不谢
    web开发快速提高工作效率的一些资源
    web开发快速提高工作效率的一些资源
    基础知识(5)- 继承
    51 NOD 1384 全排列(STL 搜索)
  • 原文地址:https://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/p/12041953.html
Copyright © 2011-2022 走看看