Leetcode 1008: Construct Binary Search Tree from Preorder Traversal

grid47
grid47
Exploring patterns and algorithms
Jul 29, 2024 5 min read

You are given an array representing the preorder traversal of a binary search tree (BST). Your task is to construct the BST from this preorder traversal and return the root of the tree.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of integers representing the preorder traversal of a BST. The array will have a length of at least 1 and at most 100, with each integer between 1 and 1000.
Example: preorder = [10, 5, 1, 7, 15, 12]
Constraints:
• 1 <= preorder.length <= 100
• 1 <= preorder[i] <= 1000
• All elements in the preorder array are unique.
Output: Return the root of the binary search tree constructed from the given preorder traversal.
Example: Output: [10,5,15,1,7,null,12]
Constraints:
• The output is the root of the binary search tree in level-order traversal.
Goal: The goal is to construct a binary search tree from the preorder traversal. Each node in the tree should satisfy the BST property where the left child is less than the parent and the right child is greater than the parent.
Steps:
• Start with the first element of the preorder array as the root of the tree.
• For each subsequent element, place it in the correct position in the tree following the BST rules.
• Continue this process until all elements are placed in the tree.
Goal: Ensure the solution can handle up to the maximum constraint efficiently.
Steps:
• The preorder array will always have at least one element and at most 100 elements.
Assumptions:
• The preorder array contains unique values and forms a valid BST.
Input: Input: preorder = [10, 5, 1, 7, 15, 12]
Explanation: In this case, we can construct the following BST: [10, 5, 15, 1, 7, null, 12]. The first element 10 becomes the root, then 5 goes to the left of 10, 1 goes to the left of 5, and so on.

Input: Input: preorder = [15, 10, 5, 12, 20, 17]
Explanation: For this input, the BST would look like [15, 10, 20, 5, 12, null, 17]. Starting with 15 as the root, 10 goes to the left, 20 goes to the right, and so on.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus