劍指Offer-7 重建二叉樹
阿新 • • 發佈:2018-12-04
題目:
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
連結:
思路:
解答:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回構造的TreeNode根節點
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin or len(pre) != len(tin): return
return self.reconstruct(pre, tin, 0, len(pre)-1, 0, len(tin)-1)
def reconstruct(self, pre, tin, preStart, preEnd, tinStart, tinEnd):
rootValue = pre[preStart]
rootIndex = tin.index(rootValue)
root = TreeNode(rootValue)
if preStart == preEnd:
return root
if rootIndex > tinStart:
root.left = self.reconstruct(pre, tin, preStart + 1, rootIndex - tinStart + preStart, tinStart, rootIndex - 1)
if tinEnd > rootIndex:
root.right = self.reconstruct(pre, tin, rootIndex - tinStart + preStart + 1, preEnd, rootIndex + 1, tinEnd)
return root