Construct a BT from Postorder and Inorder

Binary Trees Construction Problems Hard
  • Fun Fact: This problem is directly relevant in the world of computer graphics and rendering
  • Particularly, it's used in algorithms for "Binary Space Partitioning" - a method often employed in 3D computer graphics for rendering scenes with a large number of overlapping objects
  • Constructing binary trees using preorder and inorder traversals is crucial in defining the ordering and space divisions
  • Not to forget, such problems also have substantial uses in designing compilers and databases

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


Construct and return the binary using inorder and preorder arrays.

Examples:

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

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

Explanation : The output tree is shown below.

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

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

Explanation : The output tree is shown below.

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

Constraints

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

Hints

  • Locate the root in the inorder array to determine: Left subtree nodes (all nodes to the left of the root in inorder). Right subtree nodes (all nodes to the right of the root in inorder).
  • Recursively build the left and right subtrees using the respective subarrays from postorder and inorder.

Company Tags

Red Hat Medtronic Teladoc Health Uber PwC ARM Square Bain & Company Cloudflare Chewy IBM NVIDIA Target Deloitte American Express Qualcomm Instacart Intel Seagate Technology Epic Games JPMorgan Chase OYO Rooms Johnson & Johnson Splunk Activision Blizzard Google Microsoft Amazon Meta Apple Netflix Adobe