Construct Binary Search Tree from Preorder Traversal — LeetCode 1008 Python Solution
- Problem
- #1008
- Pattern
- Stack
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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 there is always possible to find a binary search tree with the given requirements for the given test cases.
Example
- Input
- preorder = [8,5,1,7,10,12]
- Output
- [8,5,10,1,7,null,12]
Python solution
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
def dfs(i: int, j: int) -> Optional[TreeNode]:
if i > j:
return None
root = TreeNode(preorder[i])
l, r = i + 1, j + 1
while l < r:
mid = (l + r) >> 1
if preorder[mid] > preorder[i]:
r = mid
else:
l = mid + 1
root.left = dfs(i + 1, l - 1)
root.right = dfs(l, j)
return root
return dfs(0, len(preorder) - 1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1008. Construct Binary Search Tree from Preorder Traversal is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1008. Construct Binary Search Tree from Preorder Traversal?
- LeetCode 1008. Construct Binary Search Tree from Preorder Traversal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1008. Construct Binary Search Tree from Preorder Traversal?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 1008. Construct Binary Search Tree from Preorder Traversal?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1008. Construct Binary Search Tree from Preorder Traversal cover?
- LeetCode 1008. Construct Binary Search Tree from Preorder Traversal is tagged Stack, Tree, Binary Search Tree, Array, Binary Tree and Monotonic Stack on LeetCode.