2018-11-21 leetcode Construct Binary Tree from Preorder and Inorder Traversal Construct Binary Tree from Preorder and Inorder TraversalRecursive Version - 148ms 1234567891011121314151617181920# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if inorder: idx = inorder.index(preorder.pop(0)) root = TreeNode(inorder[idx]) root.left = self.buildTree(preorder, inorder[0:idx]) root.right = self.buildTree(preorder, inorder[idx+1:]) return root test code 123456789101112131415161718192021222324252627282930313233343536373839404142In [39]: class TreeNode: ...: def __init__(self, x): ...: self.val = x ...: self.left = None ...: self.right = NoneIn [50]: # Definition for a binary tree node. ...: # class TreeNode: ...: # def __init__(self, x): ...: # self.val = x ...: # self.left = None ...: # self.right = None ...: ...: class Solution: ...: def buildTree(self, preorder, inorder): ...: """ ...: :type preorder: List[int] ...: :type inorder: List[int] ...: :rtype: TreeNode ...: """ ...: if inorder: ...: idx = inorder.index(preorder.pop(0)) ...: root = TreeNode(inorder[idx]) ...: root.left = self.buildTree(preorder, inorder[0:idx]) ...: root.right = self.buildTree(preorder, inorder[idx+1:]) ...: return root In [52]: pre_o = [3,9,20,15,7]In [53]: in_o = [9,3,15,20,7]In [54]: s = Solution(); t = s.buildTree(pre_o, in_o); print(t)<__main__.TreeNode object at 0x10d8128d0>In [55]: t.right.valOut[55]: 20In [56]: t.right.left.valOut[56]: 15In [57]: t.right.right.valOut[57]: 7 leet code Newer Serialize and Deserialize Binary Tree Older Set Matrix Zeroes