1 """ 2 For example, given 3 preorder = [3,9,20,15,7] 4 inorder = [9,3,15,20,7] 5 Return the following binary tree: 6 3 7 / 8 9 20 9 / 10 15 7 11 """ 12 class TreeNode: 13 def __init__(self, x): 14 self.val = x 15 self.left = None 16 self.right = None 17 class Solution(object): 18 def buildTree(self, preorder, inorder): 19 if len(preorder) == 0: 20 return None 21 root_val = preorder[0] 22 root_index = inorder.index(root_val) 23 result = TreeNode(root_val) 24 left_preorder = preorder[1:root_index+1] #比如L=[5,3,6] 25 right_preorder = preorder[root_index+1:] #L[1:3] == [3,6] 26 left_inorder = inorder[:root_index] #实际index是1,2 27 right_inorder = inorder[root_index+1:] 28 result.left = self.buildTree(left_preorder, left_inorder) #递归 29 result.right = self.buildTree(right_preorder, right_inorder) 30 return result 31 """ 32 常见的题,给出前序中序 求二叉树 33 leetcode106为给出中序后序 求二叉树,可相互比较 34 """