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