You are given two integer arrays, inorder and postorder. inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree. Construct the tree and return its root.
Function Signature
def build_tree(inorder: list[int], postorder: list[int]) -> Optional[TreeNode]:
Rules
-
TreeNode
is the usual binary tree node with fields
val
,
left
and
right
.
-
Inorder visits the left subtree, then the node, then the right subtree. Postorder visits the left subtree, then the right subtree, then the node.
-
The examples write a tree as its level-order list, with
None
for a missing child and trailing
None
values removed. Because all values are distinct, exactly one tree matches both traversals.
Constraints
-
1 <= len(inorder) <= 3000
-
len(postorder) == len(inorder)
-
-3000 <= inorder[i], postorder[i] <= 3000
-
inorder
and
postorder
consist of unique values.
-
Every value of
postorder
also appears in
inorder
.
-
inorder
is guaranteed to be the inorder traversal of the tree, and
postorder
the postorder traversal of the same tree.
Examples
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,None,None,15,7]
The last postorder value, 3, is the root. In inorder, 9 sits to its left and 15, 20, 7 to its right; repeating the split on the right part makes 20 the root there, with 15 on its left and 7 on its right.
Input: inorder = [-1], postorder = [-1]
Output: [-1]
A single value gives a single-node tree.
Input: inorder = [1,2,3,4], postorder = [1,3,4,2]
Output: [2,1,4,None,None,3]
The root is 2, with 1 on its left and 3, 4 on its right. In the right part, 4 comes last in postorder, so it is that subtree's root, and 3 is its left child. Node 4 has no right child, and the trailing None is dropped.