Construct a BT from Preorder and Inorder

Binary Trees Construction Problems Hard
  • Fun Fact: The concept underlying this problem is fundamental to the way databases organize and retrieve their data
  • Databases use tree structures (like Binary Search Trees) to store data, which optimizes search queries, inserts, deletes, and sequential data access
  • Efficient tree construction algorithms, like the one this problem aims to solve, are therefore vital to the database's performance
  • Also, this concept is utilized in routing protocols in network software, and the visual representation of hierarchical data, such as directory structures or organization charts in applications

Given two integer arrays preorder and inorder. Where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree.


Construct and return the binary tree using in-order and preorder arrays.

Examples:

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

Output : [3, 9, 20, null, null, 15, 7]

Explanation : The output tree is shown below.

Input : preorder = [3, 4, 5, 6, 2, 9] , inorder = [5, 4, 6, 3, 2, 9]

Output : [3, 4, 2, 5, 6, null, 9]

Explanation : The output tree is shown below.

Input : preorder = [5, 1, 8, 6, 2, 4, 7] , inorder = [8, 6, 1, 5, 4, 2, 7]

Constraints

  • 1 <= Number of Nodes <= 104
  • -104 <= Node.val <= 104
  • All values in the given tree are unique.
  • Each value of inorder also appears in preorder.
  • Preorder is guaranteed to be the preorder traversal of the tree.
  • Inorder is guaranteed to be the inorder traversal of the tree.

Hints

  • Locate the root's index in inorder. The left subtree elements are before the root index. The right subtree elements are after the root index.
  • Recursively Construct the Left and Right Subtrees Use sliced subarrays to pass correct values for left and right subtree construction.

Company Tags

ARM Zomato Morgan Stanley Rockstar Games Cerner Snowflake Epic Games GE Healthcare Qualcomm DoorDash Rakuten Roche Oracle Optum Splunk Reddit Flipkart Philips Healthcare AMD Chewy Square Johnson & Johnson Wayfair Unity Technologies Micron Technology Google Microsoft Amazon Meta Apple Netflix Adobe