Skip to main content
All Questions

Construct a binary tree given its preorder and inorder traversals.

Medium

Given two integer arrays, preorder and inorder, which represent the pre-order and in-order traversal of a binary tree, construct and return the binary tree.

  • Pre-order traversal visits nodes in this order: root → left subtree → right subtree
  • In-order traversal visits nodes in this order: left subtree → root → right subtree

You need to construct the binary tree and return its root node.

Examples

preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7] output: [3, 9, 20, null, null, 15, 7] Explanation: Given the two arrays, the binary tree constructed is: 3 / \ 9 20 / \ 15 7
preorder = [1, 2], inorder = [2, 1] output: [1, 2] Explanation: Given the two arrays, the binary tree constructed is: 1 / 2

Constraints:

  • The number of nodes in the tree is in the range [1, 3000].
  • preorder and inorder consist of unique integers.
  • The elements of inorder will always be the same as the elements of preorder but in a different order.

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.