889. Construct Binary Tree from Preorder and Postorder Traversal
- Construct Binary Tree from Preorder and Postorder Traversal python solution
题目描述
Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre and post are distinct positive integers.
解析
先序遍历的顺序是 根->左->右,而后序遍历的顺序是 左->右->根,如果要建立树,那么需从根结点开始创建,然后再创建左右子结点。由于先序和后序各自的特点,根结点的位置是固定的,既是先序遍历数组的第一个,又是后序遍历数组的最后一个。知道了根结点的位置后,我们需要分隔左右子树的区间,先序和后序的各个区间表示如下:
preorder -> [root] [left subtree] [right subtree]
postorder -> [left subtree] [right substree] [root]
具体到题目中的例子就是:
preorder -> [1] [2,4,5] [3,6,7]
postorder -> [4,5,2] [6,7,3] [root]
先序和后序中各自的左子树区间的长度肯定是相等的,但是其数字顺序可能是不同的,可以发现先序左子树区间的第一个数字2,在后序左右子树区间的最后一个位置,而且这个规律对右子树区间同样适用。
因为先序遍历的顺序是 根->左->右,而后序遍历的顺序是 左->右->根,其实这个2就是左子树的根结点,所以会一个在开头,一个在末尾了。我们就可以根据‘2’这个数字,来定位左右子树区间的位置范围。
class Solution:
def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:
if not pre and not post:
return None
if pre[0]==post[0]:
return TreeNode(pre[0])
root = TreeNode(pre[0])
i,j=1,0
while pre[i]!=post[j]:
j+=1
root.left=self.constructFromPrePost(pre[1:j+2],post[0:j+1])
root.right=self.constructFromPrePost(pre[j+2:],post[j+1:-1])
return root
Reference
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/238787/Python-recursive-O(N)-with-detailed-explanation-and-example
https://www.cnblogs.com/grandyang/p/10909191.html