LeetCode-Python-889. 根据前序和后序遍历构造二叉树

返回与给定的前序和后序遍历匹配的任何二叉树。

 pre 和 post 遍历中的值是不同的正整数。

示例:

输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]

提示:

  • 1 <= pre.length == post.length <= 30
  • pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列
  • 每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。

思路:

跟105,106几乎一样的思路。

前序与中序遍历序列构造二叉树  - CSDN博客

LeetCode-Python-106. 从中序与后序遍历序列构造二叉树  - CSDN博客

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

根据不同遍历顺序的特点可以得到左或右子树的长度或者遍历,然后在已有的遍历里切割就好了。

class Solution(object):
    def constructFromPrePost(self, pre, post):
        """
        :type pre: List[int]
        :type post: List[int]
        :rtype: TreeNode
        """
        
        l1, l2 = len(pre), len(post)
        if l1 == 0 or l2 == 0:
            return 
        
        root = TreeNode(pre[0])
        if l1 == 1:
            return root
        
        pos = post.index(pre[1]) #pos代表左子树的元素在post里最右出现的位置
        len_left = pos + 1
        
        pre_left = pre[1:len_left + 1]
        post_left = post[:pos + 1]
        
        pre_right = pre[len_left +1:]
        post_right = post[pos + 1: -1]
        
        # print pre_left, post_left
        # print pre_right, post_right
        root.left = self.constructFromPrePost(pre_left, post_left)
        root.right = self.constructFromPrePost(pre_right, post_right)
        
        return root

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/89285677