1. 程式人生 > >前序中序構建二叉樹

前序中序構建二叉樹

[] pri light index blog log highlight tree cnblogs

    public Node PreMidToTree(int[] pre,int[] mid)
    {
        if (pre == null || mid == null)
            return;
        Dictionary<int, int> dic = new Dictionary<int, int>();
        for (int i = 0; i < mid.Length; i++)
            dic[mid[i]] = i;
        return PreMid(pre, 0, pre.Length - 1, mid, 0, mid.Length - 1, dic);

    }

    private Node PreMid(int[] pre, int ps, int pe, int[] mid, int ms, int me, Dictionary<int, int> dic)
    {
        if (ps > pj)
            return null;
        Node head = new Node(p[pi]);
        int index = dic[pre[ps]];
        head.left = PreMid(pre,ps+1,ps+index-ms,mid,ms,index-1,dic);
        head.right = PreMid(pre, ps + 1, ps + index - ms, mid, ms, index - 1, dic);
        return head;
    }

  

前序中序構建二叉樹