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