Construct Binary Tree from Inorder and Postorder

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given two integer arrays describing the same binary tree: inorder (left subtree, node, right subtree) and postorder (left subtree, right subtree, node). All values in the tree are **distinct**, which makes the tree uniquely determined. Rebuild the tree and return its root; the grader serializes it in level order. A hash map from value to inorder index lets you split each subtree in O(1), giving O(n) overall.

Examples

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
The last postorder value 3 is the root; in inorder, [9] lies to its left and [15,20,7] to its right.
Input: inorder = [-1], postorder = [-1]
Output: [-1]
A single node.

Constraints

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= values <= 3000
  • Values are distinct, and both arrays describe the same tree

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems