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 的排列
每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。
这道题和之前的使用 中前; 中后类似,但是这里使用前后不能唯一确定左子树和右子树,并且我们在处理左子树的根节点pre[ 1 ]的时候,需要对递归中的pre长度进行考虑。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:
if not pre and not post: return
if len(pre) == 1: return TreeNode(pre[0])
index = post.index(pre[1])+1#这里表示的是左子树序列的长度,所以要加以
root = TreeNode(pre[0])
root.left = self.constructFromPrePost(pre[1:index+1], post[:index])
root.right = self.constructFromPrePost(pre[index+1:], post[index:-1])
return root