天天看點

重建二叉樹(牛客網(三))

輸入某二叉樹的前序周遊和中序周遊的結果,請重建出該二叉樹。假設輸入的前序周遊和中序周遊的結果中都不含重複的數字。例如輸入前序周遊序列{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) {
        TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
        return root;
    }

 private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
         
        if(startPre>endPre||startIn>endIn)
            return null;
        TreeNode root=new TreeNode(pre[startPre]);
         
        for(int i=startIn;i<=endIn;i++)
            if(in[i]==pre[startPre]){
                root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
                root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
                      break;
            }
                 
        return root;
    }  
}
           

我們可以先根據前序周遊序列的第一個數字建立根節點,接下來在中序周遊序列中找到根節點的位置。這樣就能确定左、右子樹結點的數量,在前序周遊和中序周遊

中劃分左、右子樹結點的值之後,我麼就可以遞歸的調用函數。

繼續閱讀