Description
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.
If there exist multiple answers, you can return any of them.
Β
Example 1:
Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7]
Example 2:
Input: preorder = [1], postorder = [1] Output: [1]
Β
Constraints:
1 <= preorder.length <= 301 <= preorder[i] <= preorder.length- All the values of
preorderare unique. postorder.length == preorder.length1 <= postorder[i] <= postorder.length- All the values of
postorderare unique. - It is guaranteed that
preorderandpostorderare the preorder traversal and postorder traversal of the same binary tree.
Solution
Python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
N = len(preorder)
mp = {}
for i, x in enumerate(postorder):
mp[x] = i
# pre = [root, left, right]
# post = [left, right, root]
def go(preLeft, preRight, postLeft, postRight):
if preLeft > preRight: return None
node = TreeNode(preorder[preLeft])
if preLeft == preRight:
return node
val = preorder[preLeft + 1]
idx = mp[val]
offset = idx - postLeft
node.left = go(preLeft + 1, preLeft + 1 + offset, postLeft, idx)
node.right = go(preLeft + 1 + offset + 1, preRight, idx + 1, postRight)
return node
return go(0, N - 1, 0, N - 1)