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
and postorder
consist of unique values.postorder
also appears in inorder
.inorder
and postorder
consist of unique values.To build the binary tree from inorder and postorder traversals, we can use the following strategy:
postorder
list is the root of the tree.inorder
list into left and right subtrees using the root’s index.inorder
list to recursively construct the left and right subtrees.Steps:
inorder
array to quickly locate the root and partition indices.postorder
list and partitioning the inorder
array accordingly.# 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
def buildTree(inorder, postorder):
if not inorder or not postorder:
return None
# Mapping of inorder values to their indices for quick lookup
inorder_index_map = {value: idx for idx, value in enumerate(inorder)}
def helper(in_left, in_right):
if in_left > in_right:
return None
# The last element in postorder is the root of the current tree
root_val = postorder.pop()
root = TreeNode(root_val)
# Split the inorder list into left and right subtrees
index = inorder_index_map[root_val]
# Recursively construct the right subtree
root.right = helper(index + 1, in_right)
# Recursively construct the left subtree
root.left = helper(in_left, index - 1)
return root
# Start with the full range of the inorder list
return helper(0, len(inorder) - 1)
# Example Usage
inorder = [9, 3, 15, 20, 7]
postorder = [9, 15, 7, 20, 3]
tree = buildTree(inorder, postorder)
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?