1. 程式人生 > >劍指offer 重建二叉樹

劍指offer 重建二叉樹

題目描述

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

package Tree;
public class Solution {
    public static void main(String[] args) {
        //測試
        int[] pre= {1,2,4,7,3,5,6,8};
        int[] in= {4,7,2,1,5,3,8,6};
        TreeNode treeNode=reConstructBinaryTree(pre,in);
        System.out.println(treeNode.toString());
    }

    public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {

        TreeNode treeNode=new TreeNode(pre[0]);
        //獲取根節點在中序遍歷陣列中是位置
        int RootIndex=0;
        for(int i=0;i<in.length;i++) {
            if(in[i]==pre[0]) {
                RootIndex=i;
            }
        }
        //將先序的遍歷結果分成兩份,一份是左子樹,一份是右子樹
        int[] preLeft=new int[RootIndex];
        int[] preRight=new int[pre.length-RootIndex-1];
        for(int i=0;i<RootIndex;i++) {
            preLeft[i]=pre[i+1];
        }
        for(int i=0;i<pre.length-RootIndex-1;i++) {
            preRight[i]=pre[RootIndex+1+i];
        }
        //將中序的遍歷的結果分為兩份,一份是左子樹,一份是右子樹
        int[] midLeft=new int[RootIndex];
        int[] midRight=new int[in.length-RootIndex-1];
        for(int i=0;i<RootIndex;i++) {
            midLeft[i]=in[i];
        }
        for(int i=0;i<in.length-RootIndex-1;i++) {
            midRight[i]=in[RootIndex+i+1];
        }
        if(in.length>0&pre.length>0) {
            if(preLeft.length>0) {
                treeNode.left=reConstructBinaryTree(preLeft,midLeft);
            }
            if(preRight.length>0) {
                treeNode.right= reConstructBinaryTree(preRight,midRight);
            }
        }
        return treeNode;
    }
}