Construct Binary Search Tree from Preorder Traversal
LeetCode 1008 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Pre-order index + upper bound recursion.
मी Construct Binary Search Tree from Preorder Traversal (LeetCode 1008) असा सोडवला — Construction / Serialization पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
Consume the pre-order list left to right. Each value becomes a node, its left subtree takes the following values smaller than it, and its right subtree takes values up to the ancestor's bound.
Approach
- 1
dfs(bound): stop if the list is used up or the next value exceeds bound.
- 2
Create a node and advance the index.
- 3
left = dfs(node.val); right = dfs(bound).
मी कसा सोडवला
Bounded pre-order recursionPythonO(n) time
class Solution:
def bstFromPreorder(self, preorder):
self.i = 0
def dfs(preorder, upperBound):
if self.i == len(preorder) or preorder[self.i] > upperBound:
return None
root = TreeNode(preorder[self.i])
self.i += 1
root.left = dfs(preorder, root.val)
root.right = dfs(preorder, upperBound)
return root
return dfs(preorder, float("inf"))Construct Binary Search Tree from Preorder Traversal — वारंवार विचारले जाणारे प्रश्न
Construct Binary Search Tree from Preorder Traversal मागील intuition काय आहे?
Consume the pre-order list left to right. Each value becomes a node, its left subtree takes the following values smaller than it, and its right subtree takes values up to the ancestor's bound.
Construct Binary Search Tree from Preorder Traversal (LeetCode 1008) कसा सोडवावा?
1. dfs(bound): stop if the list is used up or the next value exceeds bound. 2. Create a node and advance the index. 3. left = dfs(node.val); right = dfs(bound).
Construct Binary Search Tree from Preorder Traversal ची time आणि space complexity किती आहे?
Time: O(n). Space: O(h). (Accepted approach: Bounded pre-order recursion.)
Construct Binary Search Tree from Preorder Traversal मध्ये सामान्य चुका कोणत्या?
Inserting values one by one is O(n²) for sorted input.