Array:通过前序和中序数组生成后序数组

2016-05-23  本文已影响34人  敲一手烂代码
public int[] getPosArray(int[] pre,int[] in) {
        if (pre==null||in==null) {
            return null;
        }
        int[] pos  = new int[pre.length];
        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < in.length; i++) {
            hashMap.put(in[i], i);
        }
        setPos(pre, 0, pre.length-1, in, 0, in.length-1, pos, pos.length-1, hashMap);
        return pos;
    }
    public int setPos(int[] pre,int pi,int pj,int[] in,int ni,int nj,int[] pos,int s,HashMap<Integer, Integer> hashMap) {
        if (pi>pj) {
            return s;
        }
        pos[s--] = pre[pi];
        int index = hashMap.get(pre[pi]);
        s = setPos(pre, pi+1+(nj-index), pj, in, index+1, nj, pos, s, hashMap);
        return setPos(pre, pi+1, pi+index-ni, in, ni, index-1, pos, s, hashMap);
    }
上一篇下一篇

猜你喜欢

热点阅读