Skip to interview prep
Apexed

90. Build a Tree From Preorder and Inorder

MediumTrees

Given the preorder and inorder traversals of a binary tree with distinct values, rebuild the tree and return its root.

A binary tree is passed as TreeNode objects with val, left and right. The tests write trees in level order, with null for a missing child.

Example 1

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

Constraints

  • 0 ≤ nodes ≤ 3000
  • Values are distinct
  • Both arrays describe the same tree

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 5 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Build a Tree From Preorder and Inorder — coding interview practice — Apexed