根据两种遍历来构建二叉树

本题目只是以中序后序遍历作为例子,其他的两种也是一样的。

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        ### 构建辅助函数
        def helper(inorder, postorder, inorder_left, inorder_right, postorder_left, postorder_right):
            ### 空
            if inorder_left > inorder_right:
                return None
             
            ### 根据遍历的特点,先找到根,重建树
            root = TreeNode(postorder[postorder_right])  ### 构造树
            if postorder_left == postorder_right:  ### 如果只有根节点,就直接返回结果
                return root
            
            local = inorder.index(postorder[postorder_right])  ### 在中序遍历中寻找root的位置
            size = local - inorder_left  ### 判断左子树长度

            root.left = helper(inorder, postorder, inorder_left, local-1, postorder_left, postorder_left+size-1) ### 这个二叉树在中后遍历中左子树的长度需要计算清楚,千万不能包括根节点。
            ### 如果左子树只有一个,那么这个是inorder_left=local-1
            root.right = helper(inorder, postorder, local+1, inorder_right, postorder_left+size, postorder_right-1)
            return root
        return helper(inorder, postorder, 0, len(inorder)-1, 0, len(postorder)-1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值