Construct Tree from Preorder and Inorder

35 min · buildTree()

Two guest lists record the same tree in different orders. Put them together, and every left and right branch becomes recoverable.

You're given two arrays containing the same unique integer values:

  • preorder traversal visits a node before its left and right subtrees.
  • inorder traversal visits the left subtree, then the node, then the right subtree.

Reconstruct the binary tree and return its root. The judge serializes your returned tree as a level-order array, using null for missing children, so it can compare the shape as well as the values.

A few ground rules:

  • preorder and inorder always describe the same tree.
  • Values are unique, so each root has one unambiguous position in inorder.
  • Two empty arrays describe an empty tree; return null, which serializes as [].

Constraints

  • 0 <= preorder.length == inorder.length <= 10_000
  • All values are unique.
  • -2_147_483_648 <= preorder[i], inorder[i] <= 2_147_483_647
  • preorder and inorder are consistent traversals of the same tree.

Hints

The first root is free

The first value in preorder must be the root. Find that value in inorder; what do the values on its left and right represent?

Measure the left subtree

If the root splits inorder after left_size values, the next left_size preorder values belong to the left subtree. That gives both recursive ranges.

Stop searching for the split

Repeatedly scanning inorder can become quadratic on a one-sided tree. Build a map from value to inorder index once, then every split is an O(1) lookup.

Follow-up

Why does this reconstruction become ambiguous when values may repeat, and what extra information would you need to remove that ambiguity?

Visible cases

Examples

Example 1

ready
Input
preorder = [
  3,
  9,
  20,
  15,
  7
]
inorder = [
  9,
  3,
  15,
  20,
  7
]
Expected
[
  3,
  9,
  20,
  null,
  null,
  15,
  7
]
Why
3 is the preorder root; inorder places 9 left and the 20 subtree right

Example 2

ready
Input
preorder = [
  -1
]
inorder = [
  -1
]
Expected
[
  -1
]
Why
one value reconstructs one node

Example 3

ready
Input
preorder = []
inorder = []
Expected
[]
Why
empty traversals reconstruct an empty tree

Interview signal

Asked at

AmazonGoogleBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite