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).