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.