AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Construct Binary Tree from Inorder and Postorder Traversal

The key idea

The last element of postorder is always the current root. Find that root inside inorder: everything to its left is the left subtree, everything to its right is the right subtree. Consume postorder from the back, building the right subtree before the left, because that is the reverse of how postorder lists them.

Problem

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.

Every value in the tree is distinct, and each value of postorder also appears in inorder. You may rely on both traversals being valid for one and the same tree.

Constraints

Examples

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] Output: [3,9,20,null,null,15,7]
Input: inorder = [-1], postorder = [-1] Output: [-1]

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems