代码随想录算法训练营第十六天(二叉树篇)

构造二叉树

106. 从中序与后序遍历序列构造二叉树

题目链接:106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

题目思路:

  1. 如果后续数组为空,返回空节点。
  2. 通过后序的最后一个元素确定二叉树的根节点。
  3. 根据根节点切割中序数组:左中序,右中序。
  4. 根据左中序的长度,切割后序数组:左后序,右后序。
  5. 递归得到根节点的左子树:将左中序和左后序放入函数中递归。
  6. 递归得到根节点的右子树:将右中序和右后续放入函数中递归。
  7. 返回根节点。

自己跟这个思路动手画一下,思路变清晰了,感觉比上次的递归好理解。

class Solution(object):
    def buildTree(self, inorder, postorder):
        # inorder: 中序,左中右
        # postorder: 后序:左右中\
        # 1. 检查后序数组是否为空。
        if not postorder:
            return None
        # 2. 寻找根节点
        rootVal = postorder[-1]
        root = TreeNode(rootVal)
        # 3. 分割中序数组
        separateIndex = inorder.index(rootVal)
        inLeft = inorder[:separateIndex]
        inRight = inorder[separateIndex+1:]
        # 4. 分割后序数组
        postLeft = postorder[:len(inLeft)]
        postRight = postorder[len(inLeft):len(postorder) - 1]
        # 5. 递归得到左子树
        root.left = self.buildTree(inLeft, postLeft)
        # 6. 递归得到右子树
        root.right = self.buildTree(inRight, postRight)
        # 7. 返回结果!
        return root

105. 从前序和中序遍历序列构造二叉树

题目链接:105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

class Solution(object):
    def buildTree(self, preorder, inorder):
        # preorder: 前序,中左右
        # inorder:  中序, 左中右
        if not inorder:
            return None

        # 建立根节点
        rootVal = preorder[0]
        root = TreeNode(rootVal)

        # 切割中序数组
        separateIndex = inorder.index(rootVal)
        inLeft = inorder[:separateIndex]
        inRight = inorder[separateIndex+1:]

        # 切割前序数组
        preLeft = preorder[1:len(inLeft) + 1]
        preRight = preorder[len(inLeft) + 1:len(preorder)]

        # 递归得到左子树
        root.left = self.buildTree(preLeft, inLeft)
        # 递归得到右子树
        root.right = self.buildTree(preRight, inRight)
        
        return root
        

654. 最大二叉树

题目链接:654. 最大二叉树 - 力扣(LeetCode)

练习了上面两道,这道就比较容易做出来。找到数组中最大的元素和,设为root,根据其对应的下标将数组分为左子树和右子树,分别放入递归即可。

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        if not nums:
            return None
        root_val = max(nums)
        root = TreeNode(root_val)
        root_index = nums.index(root_val)
        left = nums[:root_index]
        '''if left == []:
            left = None'''
        right = nums[root_index + 1: len(nums)]
        '''if right == []:
            right = None'''
        root.left = self.constructMaximumBinaryTree(left)
        root.right = self.constructMaximumBinaryTree(right)

        return root
        

  • 17
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值