Construct Binary Tree from Preorder and Inorder Traversal

MediumTrees

You get two arrays of the same distinct values: preorder, the order a preorder walk (node, left subtree, right subtree) visits a binary tree, and inorder, the order an in-order walk (left subtree, node, right subtree) visits the same tree. Build that tree and return its root.

On this page the tree you return is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  preorder = [5, 2, 1, 8, 9], inorder = [1, 2, 5, 8, 9]
Output: [5, 2, 8, 1, null, null, 9]

5 comes first, so it is the root. In inorder, 1 and 2 sit left of it and 8 and 9 right of it.

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

One value makes a tree of one node.

Constraints

  • 1 ≤ preorder.length ≤ 3000, and inorder has the same length.
  • -3000 ≤ preorder[i], inorder[i] ≤ 3000
  • The values are distinct, and both arrays come from the same tree.

Stuck?

Hint 1

The first value of preorder is the root. Find it in inorder: the values before it form the left subtree, and the values after it form the right subtree.

Hint 2

The size of the left part tells you how many values after the root in preorder belong to the left subtree; the rest belong to the right. Recurse on both parts, and keep a Map from value to index in inorder so each lookup is O(1).

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur