Construct Binary Tree from Preorder and Inorder Traversal

Medium#105build a tree

You get two traversals of the same binary tree with distinct values: preorder (node, left subtree, right subtree) and inorder (left subtree, node, right subtree). Rebuild the tree. Our traversals: preorder [1, 7, 3, 4, 5, 6], inorder [3, 7, 4, 1, 5, 6] — the tree, level by level, is [1, 7, 5, 3, 4, none, 6].

input
preorder and inorder: the preorder (root, left, right) and inorder (left, root, right) traversals of one binary tree whose values are all different.
returns
The root of that tree: there is only one, since the values are all different.
constraints
  • 1 ≤ preorder.length ≤ 3000
  • inorder.length = preorder.length
  • −3000 ≤ preorder[i], inorder[i] ≤ 3000
  • the values of preorder are all different
  • preorder and inorder are traversals of the same tree
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
function buildTree(preorder, inorder) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more divide and conquer problems

Pattern “Divide and conquer” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.