Given two integer arrays inorder
and postorder
where inorder
is the inorder traversal of a binary tree and postorder
is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Constraints:
-
1 <= inorder.length <= 3000
-
postorder.length == inorder.length
-
-3000 <= inorder[i], postorder[i] <= 3000
-
inorder
andpostorder
consist of unique values. - Each value of
postorder
also appears ininorder
. -
inorder
is guaranteed to be the inorder traversal of the tree. -
postorder
is guaranteed to be the postorder traversal of the tree.
SOLUTION:
# 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 getRoot(self, p, q):
return max((i for i in range(p, q)), key = lambda x: self.valIndex[self.inorder[x]])
def buildTreeRec(self, p, q):
if p < q:
root = TreeNode()
currRoot = self.getRoot(p, q)
root.val = self.inorder[currRoot]
if currRoot > p:
root.left = TreeNode()
root.left = self.buildTreeRec(p, currRoot)
if currRoot < q - 1:
root.right = TreeNode()
root.right = self.buildTreeRec(currRoot + 1, q)
return root
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
n = len(postorder)
self.inorder = inorder
self.valIndex = {}
for i, item in enumerate(postorder):
self.valIndex[item] = i
return self.buildTreeRec(0, n)
Top comments (0)