Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 98 · BST

Validate Binary Search Tree

LeetCode 98 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Pass (min, max) bounds down the tree.

ಮಧ್ಯಮTreeDepth-First SearchBinary Search TreeBinary Tree
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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. 1

    validate(node, max, min).

  2. 2

    Fail if node.val ≥ max or ≤ min.

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