Practice · Trees · 11 of 12

Rebuild a Binary Tree from Two Traversals

You are given two lists describing the same binary tree, whose values are all different:

  • preorder lists the values in preorder: a node, then its left subtree, then its right subtree.
  • inorder lists them in inorder: a node's left subtree, then the node, then its right subtree.

Build the tree and return its root.

The answer is checked as the tree written in level order, row by row from the top, with null where a node is missing: [4, 2, 7, null, 3] is 4 at the root, 2 and 7 below it, and 3 as the right child of 2.

Example 1

Input
preorder = [5, 2, 1, 4, 8, 9], inorder = [1, 2, 4, 5, 8, 9]
Output
[5, 2, 8, 1, 4, null, 9]
5 comes first in the preorder, so it is the root. In the inorder, 1, 2 and 4 come before it (the left subtree) and 8 and 9 after it (the right subtree).

Example 2

Input
preorder = [1, 2], inorder = [1, 2]
Output
[1, null, 2]
Nothing comes before 1 in the inorder, so its left subtree is empty and 2 is its right child.

Constraints

  • Both lists hold the same 1 to 1000 values.
  • Values are distinct, between −3000 and 3000.
  • The tree is at most 100 levels deep.