力扣--根据前序、中序和后序来重建二叉树

二叉树的前序、中序和后序遍历:

  • 前序:根节点、左子树、右子树
  • 中序:左子树、根节点、右子树
  • 后序:左子树、右子树、根节点

一、根据前序中序来重建二叉树(剑指offer07题

1、题目:输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

2、示例

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

3、解题思路

核心思路都是要找下一次递归左子树所需的两个变量和右子树所需的两个变量。

在前序遍历结果中,最左边的元素preorder[0]就是二叉树的根节点,而在中序遍历的结果中,找到preorder[0]元素对应的下标,那么preorder[0]左边所有的元素是属于preorder[0]为根的左子树,preorder[0]右边的元素是以preorder[0]为根的右子树,然后进行递归。

4、代码

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if len(preorder)==0:return
        root=TreeNode(preorder[0])
        root_index=inorder.index(root.val)

        root.left=self.buildTree(preorder[1:root_index+1],inorder[:root_index])
        root.right=self.buildTree(preorder[root_index+1:],inorder[root_index+1:])
        return root

二、根据中序后序来重建二叉树(力扣106题

只需要把前序和中序重建二叉树中的preorder[0]改为preorder[-1],因为后序遍历中根节点为最后一位,其他相同。

代码:

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if len(postorder)==0:return
        root=TreeNode(postorder[-1])
        root_index=inorder.index(root.val)

        left_inorder=inorder[:root_index]
        right_inorder=inorder[root_index+1:]

        len_left=len(left_inorder)

        left_postorder=postorder[:len_left]
        right_postorder=postorder[len_left:-1]

        root.left=self.buildTree(left_inorder,left_postorder)
        root.right=self.buildTree(right_inorder,right_postorder)

        return root

三、根据前序后序来重建二叉树(力扣889题

获取左子树中一共有多少个节点,同时也就知道了右子树总的节点数。前序遍历的第二个元素为左子树的根节点,在后序遍历中找到这个节点,并获取其下标,则该下标加1就是左子树总元素的个数。

代码:

class Solution(object):
    def constructFromPrePost(self, pre, post):
        if not pre:
            return None
        root = TreeNode(pre[0])
        if len(pre) == 1:
            return root

        left_num = post.index(pre[1]) + 1

        left_pre, right_pre = pre[1:left_num+1], pre[left_num+1:]
        left_post, right_post = post[:left_num], post[left_num:-1]

        root.left = self.constructFromPrePost(left_pre, left_post)
        root.right = self.constructFromPrePost(right_pre, right_post)
        return root

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值