You are given two integer arrays, inorder and postorder. The inorder array records the node values of a binary tree during an inorder traversal (left, root, right), and postorder records them during a postorder traversal (left, right, root).
All values are distinct. Build the binary tree that produces these two traversals and return its root.
Example 1
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
3 is the root because it comes last in postorder. It sits at index 1 in inorder, so [9] is the left subtree and [15,20,7] is the right subtree.
Example 2
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Only one node exists, so the tree is a single root.
Constraints
1 <= inorder.length <= 3000postorder.length == inorder.length-3000 <= inorder[i], postorder[i] <= 3000inorder and postorder consist of unique values.Each value of postorder also appears in inorder.inorder is guaranteed to be the inorder traversal of the tree.postorder is guaranteed to be the postorder traversal of the tree.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI