105 Construct Binary Tree from Preorder and Inorder Traversal

105 Construct Binary Tree from Preorder and Inorder Traversal

 这道题纯递归

class Solution:
    # @param {integer[]} preorder
    # @param {integer[]} inorder
    # @return {TreeNode}
    def buildTree(self, preorder, inorder):
        self.cur = 0
        return self.help(preorder, inorder, 0, len(inorder)-1)

    def help(self, pre, ino, s, e):
        if s > e:
            return None
        node = TreeNode(pre[self.cur])
        self.cur += 1
        if s == e:
            return node
        ind = ino.index(node.val)
        node.left = self.help(pre, ino, s, ind-1)
        node.right = self.help(pre, ino, ind+1, e)
        return node

 

posted @ 2015-08-06 01:45  dapanshe  阅读(108)  评论(0编辑  收藏  举报