刷《劍指Offer》有感Day02

寫重建二叉樹的時候,對於樹,一般解題思路是遞歸,但是對於遞歸的終止條件想了好久沒有思路,最終看了牛客網的討論區。看到一段十分簡潔的代碼:

鏈接:https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6
來源:牛客網

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;
    }
    //前序遍歷{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6}
    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;
    }
}

在函數reConstructBinaryTree中,首先根據前序遍歷找出根節點,然後再根據中序遍歷找到左子樹和右子樹的長度,分別構造出左右子樹的前序遍歷和中序遍歷序列,最後分別對左右子樹採取遞歸,遞歸跳出的條件是序列長度爲1.

int[] pre startPre endPre int[] in startIn endIn
初始時 pre 0 pre.length-1 in 0 in.length-1
左子樹 pre startPre+1 startPre+(i-startIn) in startIn i-1
右子樹 pre startPre+1+(i-startIn) in i+1 endIn

其中左子樹長度爲:i-startIn

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章