Skip to the code
cf.
+25 XP

#359 Rebuild a Layout From Two Walks

medium

A crash report captured two walks of the app's layout tree but not the tree itself: preorder (node, left, right) and inorder (left, node, right). All node values are unique.

Write rebuildLayout(preorder, inorder) that rebuilds the tree and returns its root. The two lists always describe the same valid tree. Empty lists give an empty tree.

Example 1

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

1 is the root; [4, 2, 5] is left of it in inorder and [3, 6] is right.

Example 2

Input: preorder = [7], inorder = [7]
Output: [7]

A single node.

Constraints

  • 0 <= n <= 3000
  • preorder and inorder 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).