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

    结果

  • 相关阅读:
    HDU--1212大数取模
    欧拉函数
    自制体重转换器
    常用快捷键
    Markdown基本语法
    python全栈开发day50-jquery之ajax、XmlHttpRquest
    python全栈开发day49-jquery的位置信息、事件流、事件对象,事件委托,事件绑定和解绑
    阳历转阴历算法
    python全栈开发day48-jqurey自定义动画,jQuery属性操作,jQuery的文档操作,jQuery中的ajax
    python全栈开发day47-jqurey
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8858781.html
Copyright © 2011-2022 走看看