Leecode #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,2,4,5,3,6,7]和后序遍历[4,5,2,6,7,3,1],由于前序先遍历根节点,后序最后遍历根节点,因此这两个数列可以看成[[1],[2,4,5], [3,6,7]]]和[[4,5,2], [6,7,3], [1]].可以判断出[2,4,5]是左子树,[6,7,3]是右子树,根据这个思路编写代码
# 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 len(pre) == 0:
return None
root = TreeNode(pre[0])
if len(pre) == 1:
return root
index = post.index(pre[1]) + 1
root.left = self.constructFromPrePost(pre[1:index+1], post[:index])
root.right = self.constructFromPrePost(pre[index+1:], post[index:])
return root
空间和时间上表现都一般,不过代码非常简洁,主要的耗时在找index这个地方,优化可以从这里开始入手