码迷,mamicode.com
首页 > 其他好文 > 详细

105 Construct Binary Tree from Preorder and Inorder Traversal

时间:2015-08-06 07:04:10      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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

 

105 Construct Binary Tree from Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4706290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!