zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第三章 二叉树问题 通过先序和中序数组生成后序数组

    题目

    通过先序和中序数组生成后序数组
    

    java代码

    package com.lizhouwei.chapter3;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @Description:通过先序和中序数组生成后序数组
     * @Author: lizhouwei
     * @CreateDate: 2018/4/16 21:21
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter3_22 {
        public int[] getPosArray(int[] pre, int[] in) {
            if (pre == null || in == null) {
                return null;
            }
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < in.length; i++) {
                map.put(in[i], i);
            }
            int[] pos = new int[in.length];
            preAndIn(pre, 0, pre.length - 1, in, 0, in.length - 1, pos, pos.length - 1, map);
            return pos;
        }
    
        public int preAndIn(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd, int[] pos, int posEnd, Map<Integer, Integer> map) {
            if (preStart > preEnd) {
                return posEnd;
            }
            int vlaue = pre[preStart];
            pos[posEnd--] = vlaue;
            int index = map.get(vlaue);
    
            posEnd = preAndIn(pre, preStart + index - inStart + 1, preEnd, in, index + 1, inEnd, pos, posEnd, map);
            posEnd = preAndIn(pre, preStart + 1, preStart + index - inStart, in, inStart, index - 1, pos, posEnd, map);
            return posEnd;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter3_22 chapter = new Chapter3_22();
            int[] pre = {5, 2, 1, 3, 4, 8, 6, 7, 9, 10};
            int[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            int[] pos = chapter.getPosArray(pre, in);
            System.out.println("前序数组:pre = {5, 2, 1, 3, 4, 8, 6, 7, 9, 10}");
            System.out.println("中序数组:in = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}");
            System.out.println("后序数组:pos = {1, 4, 3, 2, 7, 6, 10, 9, 8, 5}");
            System.out.println();
            System.out.print("前序和中序组成后序:");
            for (int i : pos) {
                System.out.print(i + " ");
            }
        }
    }
    

    结果

  • 相关阅读:
    [转]深度理解依赖注入(Dependence Injection)
    [转]控制反转(IOC)和依赖注入(DI)
    [转]依赖注入的概念
    [转]struct实例字段的内存布局(Layout)和大小(Size)
    异步编程模式
    HTTP协议返回代码含义
    [转]StructLayout特性
    Stack的三种含义
    FineUI登入的例子中遇到的一些问题
    编程以外积累: 如何给项目生成类似VS2008的说明文档
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8858781.html
Copyright © 2011-2022 走看看