Dashboard
#33. Construct Binary Tree From Preorder And Inorder TraversalMediumTrees

You are given two integer arrays preorder and inorder.

  • preorder is the preorder traversal of a binary tree
  • inorder is the inorder traversal of the same tree
  • Both arrays are of the same size and consist of unique values.

Rebuild the binary tree from the preorder and inorder traversals and return its root.

Example 1:

Input: preorder = [1,2,3,4], inorder = [2,1,3,4]

Output: [1,2,3,null,null,null,4]

Example 2:

Input: preorder = [1], inorder = [1]

Output: [1]

Constraints:

  • 1 <= inorder.length <= 2001.
  • inorder.length == preorder.length
  • -1000 <= preorder[i], inorder[i] <= 1000
Examples
Example 1:
Input: preorder = [1,2,3,4], inorder = [2,1,3,4]
Output: [1,2,3,null,null,null,4]
Example 2:
Input: preorder = [1], inorder = [1]
Output: [1]
Constraints
  • `1 <= inorder.length <= 2001`.
  • `inorder.length == preorder.length`
  • `-1000 <= preorder[i], inorder[i] <= 1000`
Prerequisites
Target: O(N) time • O(1) spaceArray / Hash Table / Divide and Conquer / Tree / Binary Tree
Socratic AI Tutor
Gemini 3.8 Flash
Loading editor...

Click "Run" or press Ctrl+Enter to execute test cases.