Validate Binary Search Tree
LeetCode 98 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Pass (min, max) bounds down the tree.
मैंने Validate Binary Search Tree (LeetCode 98) ऐसे हल किया — BST पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Every node must lie strictly inside a range set by its ancestors: going left tightens the upper bound to the parent's value, going right tightens the lower bound.
Approach
- 1
validate(node, max, min).
- 2
Fail if node.val ≥ max or ≤ min.
- 3
Left child gets max = node.val; right child gets min = node.val.
मैंने कैसे हल किया
Range DFSPythonO(n) time · O(h) space
class Solution:
def isValidBST(self, root):
def validateTree(node, mx=None, mn=None):
if mx is not None and node.val >= mx:
return False
if mn is not None and node.val <= mn:
return False
if node.left and not validateTree(node.left, node.val, mn):
return False
if node.right and not validateTree(node.right, mx, node.val):
return False
return True
return validateTree(root)Validate Binary Search Tree — अक्सर पूछे जाने वाले प्रश्न
Validate Binary Search Tree के पीछे intuition क्या है?
Every node must lie strictly inside a range set by its ancestors: going left tightens the upper bound to the parent's value, going right tightens the lower bound.
Validate Binary Search Tree (LeetCode 98) कैसे हल करें?
1. validate(node, max, min). 2. Fail if node.val ≥ max or ≤ min. 3. Left child gets max = node.val; right child gets min = node.val.
Validate Binary Search Tree की time और space complexity क्या है?
Time: O(n)। Space: O(h)। (Accepted approach: Range DFS।)
Validate Binary Search Tree में आम गलतियाँ क्या हैं?
Comparing only with the direct parent misses violations deeper down (example 2).