Leetcode做题日记:106. Construct Binary Tree from Inorder and Postorder Traversal(PYTHON)

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

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

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:

3

/
9 20
/
15 7
第一次的代码:
上题是根据前序中序构造树,这题是根据中序后续构造树,思路都是一样的,首先根据后序找到root,然后再分割左树序列和右树序列进行递归

		def c(i,p):
            if not i :
                return None
            root=TreeNode(p[-1])
            index=i.index(p[-1])
            root.left=c(i[:index],p[:index])
            root.right=c(i[index+1:],p[index:-1])
            return root
        return c(inorder,postorder)

200ms,排名37%

#当然递归方式有很多,也可以根据下标来递归,其实写递归的时候,只需要把起始递归过程写出来就好了
#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标

		def b(il,ir):
            if li>ir:
                return None
            val=postorder.pop()
            root=TreeNode(val)
            index=tre[val]#得到root下标
            root.left=b(il,index)#根据inorder选择左右树
            root.right=b(index+1,ir)
            return root
        tre={val:ind for ind , val in enumerate(inorder) }

188ms,排名42%

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值