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 + " ");
            }
        }
    }
    

    结果

  • 相关阅读:
    Scrapy选择器和持久化
    SQLAlchemy
    Python数据库连接池DBUtils
    flask应用上下文和g
    flask请求上下文源码解析
    flask的session源码流程和第三方组件
    430软狗不喂狗后系统起不来的问题
    VS2008 快捷键大全
    未能加载或程序集“XXXX,Version=0.0.0.0,Culter=neutral,PublicKeyToken=null”或它的某一个依赖项。试图加载格式不正确的程序。
    用vs2008打开vs2005项目
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8858781.html
Copyright © 2011-2022 走看看