題目
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
題目傳送門
注意點
遞歸的時候不僅要傳入前序的start_idx、end_idx,還要傳入中序遍歷的start_idx,end_index
代碼
class Solution:
# 返回構造的TreeNode根節點
def reConstructBinaryTree(self, pre, tin):
ans = TreeNode(0)
def cru(pre, tin, pst, ped, ist, ied):
if pst > ped or ist > ied:
return None
root = TreeNode(pre[pst])
iidx = tin.index(pre[pst])
root.left = cru(pre, tin, pst + 1, iidx-ist+pst, ist, iidx-1)
root.right = cru(pre, tin, iidx-ist+pst+1, ped, iidx+1, ied)
return root
ans = cru(pre,tin,0,len(pre)-1,0,len(pre)-1)
return ans