Skip to the code
cf.
+25 XP

#360 Rebuild a Tree From Its Build Log

medium

A build system logs targets in postorder (left subtree, right subtree, then the target), because a target is built after its sub-targets. You also have the inorder listing (left, node, right) from the project file. Target ids are unique.

Write rebuildFromLog(inorder, postorder) that returns the root of the tree that produced both lists. Empty lists give an empty tree.

Example 1

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

The last postorder value, 1, is the root.

Example 2

Input: inorder = [2,1], postorder = [2,1]
Output: [1,2]

1 is built last, so it is the root, and 2 is left of it in inorder.

Constraints

  • 0 <= n <= 3000
  • Both lists hold the same unique values.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).