☰ All problems

46. Construct Binary Tree from Preorder and Inorder Traversal

You are given two integer arrays describing the same binary tree:

  • preorder: the values in pre-order (node, then left subtree, then right subtree),
  • inorder: the values in in-order (left subtree, then node, then right subtree).

All values in the tree are unique, which makes the tree fully determined. Rebuild it and return its root.

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]

Explanation: 1 comes first in pre-order, so it is the root. In the in-order array, 4,2,5 lie to its left (left subtree) and 3,6 to its right (right subtree). Repeat on each side.

Example 2
Input: preorder = [-1], inorder = [-1]
Output: [-1]
Example 3
Input: preorder = [1,2,3], inorder = [3,2,1]
Output: [1,2,null,3]

Constraints

  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • All values are unique
  • inorder is the in-order traversal of the same tree that preorder describes
💡 Hint 1

The first value in preorder is always the root. Where does that value sit in inorder, and what does that split tell you?

💡 Hint 2

Everything left of the root in inorder is the left subtree, everything right of it is the right subtree. The sizes of those parts tell you how to slice preorder too.

💡 Hint 3

Searching inorder for every root is O(n) each time. Precompute a map from value to in-order index, and consume preorder with a single moving pointer instead of slicing arrays.

/**
 * Definition for a binary tree node (provided):
 * function TreeNode(val, left, right) { this.val = val ?? 0; this.left = left ?? null; this.right = right ?? null; }
 *
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
function buildTree(preorder, inorder) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc