Construct Binary Tree from Preorder and Inorder Traversal @ LeetCode (Python)
kitt
posted @ 2014年4月14日 13:50
in LeetCode
, 4670 阅读
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param preorder, a list of integers # @param inorder, a list of integers # @return a tree node def buildTree(self, preorder, inorder): if not inorder: return None # inorder is empty root = TreeNode(preorder[0]) rootPos = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1 : 1 + rootPos], inorder[ : rootPos]) root.right = self.buildTree(preorder[rootPos + 1 : ], inorder[rootPos + 1 : ]) return root