Skip to main content

Construct Binary Tree

MediumPremium

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.