LeetCode Notes_#104_從中序與後序遍歷序列構造二叉樹
阿新 • • 發佈:2020-08-05
LeetCode Notes_#104_從中序與後序遍歷序列構造二叉樹
LeetCodeContents
題目
根據一棵樹的中序遍歷與後序遍歷構造二叉樹。
注意:
你可以假設樹中沒有重複的元素。
例如,給出
中序遍歷 inorder =[9,3,15,20,7]
後序遍歷 postorder = [9,15,7,20,3]
返回如下的二叉樹:
3
/ \
9 20
/ \
15 7
思路分析
這一題的思路與劍指Offer_#7_重建二叉樹非常類似,是一個變式,如果掌握了分析題目的方法,那麼這一題也很容易。
唯一的區別在於遞迴呼叫的引數不一樣。參考如下圖解。
解答
class Solution {
HashMap<Integer,Integer> map = new HashMap<>();
int[] post;
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder == null || postorder == null) return null;
int inLen = inorder.length;
int postLen = postorder.length;
if (inLen == 0 || postLen == 0 || inLen != postLen) return null;
post = postorder;
for(int i = 0;i <= inLen - 1;i++){
map.put(inorder[i],i);
}
return recur(0,postLen - 1,0,inLen - 1);
}
private TreeNode recur(int postL,int postR,int inL,int inR){
if (postL > postR || inL > inR) return null;
//根節點的值是後序遍歷序列的最後一個值
int rootValue = post[postR];
TreeNode root = new TreeNode(rootValue);
int rootIdx = map.get(rootValue);
root.left = recur(postL,postR - inR + rootIdx - 1,inL,rootIdx - 1);
root.right = recur(postR - inR + rootIdx,postR - 1,rootIdx + 1,inR);
return root;
}
}
複雜度分析
時間複雜度:O(n)
,需要使用主定理分析
空間複雜度:O(n)
,map儲存了所有節點,最差情況下,遞迴呼叫n層,佔用棧空間O(n)