Construct a BST from a preorder traversal

Binary Search Trees Medium Medium
  • Fun Fact: The practical application of this programming problem is most prevalent in the development of databases and search engines
  • Binary Search Trees (BSTs) are extensively used to streamline searching and sorting processes
  • For instance, in a database with millions of records, using BSTs significantly reduces the time complexity to find a specific record
  • Also, the concept of preorder traversal is used in JavaScript frameworks like React to navigate around the Document Object Model (DOM)
  • The knowledge and ability to construct a BST from a given preorder traversal data can help in optimizing tasks related to searching, insertion, and deletion in the real-world software applications

Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.


It is guaranteed that it is always possible to find a binary search tree with the given requirements for the given test cases. Note. As there can be many possible correct answers, the compiler outputs true if the solution is correct, else false.

Examples:

Input : preorder = [8, 5, 1, 7, 10, 12]

Output : [8, 5, 10, 1, 7, null, 12]

Explanation : Below is the BST image

Input : preorder = [1, 3]

Output : [1, null, 3]

Explanation : Below is the BST image

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

Constraints

  • 1 <= preorder.length <= 100
  • 1 <= preorder[i] <= 1000
  • All the values of preorder are unique.

Hints

  • "Construct the root using preorder[0]. Recursively divide preorder into left and right subtrees: Elements smaller than root form the left subtree. Elements greater than root form the right subtree. Build the left and right subtrees recursively."
  • "Use a monotonic decreasing stack to keep track of parent nodes. Iterate over preorder, and for each value: If it’s smaller than the top of the stack, it’s the left child. If it’s greater, pop elements until finding its parent, then make it the right child."

Company Tags

NVIDIA Reddit Byju's PwC eBay Seagate Technology Salesforce Teladoc Health Stripe Morgan Stanley Oracle Bungie Visa Deloitte AMD Walmart PayPal Alibaba Airbnb Bloomberg Splunk Robinhood Texas Instruments Databricks Philips Healthcare Google Microsoft Amazon Meta Apple Netflix Adobe