Construct a BT from Preorder and Inorder

Binary Trees Construction Problems Hard

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