MediumArrayHash TableDivide and ConquerTreeBinary Tree

1 approach, code in every language

Problem description

You are given two integer arrays, preorder and inorder. The preorder array lists the node values of a binary tree in the order they are visited during a preorder traversal (root, then left subtree, then right subtree), while inorder lists them in inorder traversal order (left subtree, then root, then right subtree).

Every value in the tree is unique. Reconstruct the original binary tree and return its root.

Example 1

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

Output: [3,9,20,null,null,15,7]

3 is the root because it comes first in preorder. In inorder it sits at index 1, so [9] forms the left subtree and [15,20,7] forms the right subtree, which recursion rebuilds.

Example 2

Input: preorder = [-1], inorder = [-1]

Output: [-1]

A single value yields a tree that contains only the root node.

Constraints

  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorder and inorder consist of unique values.
  • Each value of inorder also appears in preorder.
  • preorder is guaranteed to be the preorder traversal of the tree.
  • inorder is guaranteed to be the inorder traversal of the tree.

After the pattern

Now solve one you haven't seen.

Cave Survey Rebuild is our own problem on the technique behind Construct Binary Tree from Preorder and Inorder Traversal: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free