1. 程式人生 > >劍指offer牛客系列——重建二叉樹

劍指offer牛客系列——重建二叉樹

題目描述

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

前序遍歷的順序是:根-左-右

中序遍歷的順序是:左-右-根

因此前序序列的第一個數就是根節點的值,據此值再中序序列中找到其位置,位置左側的構成二叉樹的左子樹,右側同理。

遞迴解決。注意判斷邊界。由於在前序序列與中序序列中擷取的元素個數相同,索引的相對差也相同,因此只需判斷其中一個的起始是否大於結束即可。

public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre==null || in== null|| pre.length==0|| in.length==0|| pre.length!= in.length)    return null;
        return reConstructCore(pre,0,pre.length-1,in,0,in.length-1);
    }
    public TreeNode reConstructCore(int[] pre,int pStart, int pEnd,int[] in, int iStart, int iEnd){
        if(pStart> pEnd)    return null;
        TreeNode root= new TreeNode(pre[pStart]);
        int i= iStart;
        for(;i<=iEnd; i++){
            if(in[i]== pre[pStart])    break;
        }
        root.left= reConstructCore(pre,pStart+1,pStart+i-iStart,in,iStart,i-1);
        root.right= reConstructCore(pre,pStart+i-iStart+1,pEnd,in,i+1,iEnd);
        return root;
    }
}