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