Skip to content
Decoder

Construct Binary Tree from Inorder and Postorder Traversal

Medium

Problem

You are given two lists that describe the same binary tree: inorder (left subtree, then the node, then the right subtree) and postorder (left subtree, then the right subtree, then the node). All values are unique. Rebuild the tree and return its root.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
inorder = [4, 2, 5, 1, 3], postorder = [4, 5, 2, 3, 1]
Output
[1, 2, 3, 4, 5]

Example 2

Input
inorder = [1, 2, 3], postorder = [3, 2, 1]
Output
[1, null, 2, null, 3]

Example 3

Input
inorder = [7], postorder = [7]
Output
[7]

Constraints

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • Both lists describe the same tree.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.