105. Construct Binary Tree from Preorder and Ignorer Traversal【M】【35】【再来一遍】

175 篇文章 0 订阅
157 篇文章 0 订阅

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.


Subscribe to see which companies asked this question


下面的代码内存超了,看了人家的,改成了这样。

一定要搞清前序中序是什么意思。


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def buildTree(self, preorder, inorder):
        if inorder:
            val = preorder.pop(0)
            pos = inorder.index(val)
            root = TreeNode(val)
            root.left = self.buildTree(preorder,inorder[:pos])
            root.right = self.buildTree(preorder,inorder[pos+1:])
            return root

        '''
        if not p:
            return None
        #print p,i,i.index(p[0])
        if len(p) == 1:
            return TreeNode(p[0])

        val = p[0]
        pos = i.index(val)

        root = TreeNode(val)
        root.left = self.buildTree(p[1:pos+1],i[0:pos])
        root.right = self.buildTree(p[pos+1:],i[pos+1:])
        return root
        '''

        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值