diff --git a/src/my_project/interviews/google_top_exercises/round_1/19_validate_binary_search_tree.py b/src/my_project/interviews/google_top_exercises/round_1/19_validate_binary_search_tree.py new file mode 100644 index 00000000..401027e1 --- /dev/null +++ b/src/my_project/interviews/google_top_exercises/round_1/19_validate_binary_search_tree.py @@ -0,0 +1,26 @@ +from typing import Optional + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + def validate(node: Optional[TreeNode], min_val: float, max_val: float) -> bool: + # Empty tree is valid + if not node: + return True + + # Check if current node violates BST property + if node.val <= min_val or node.val >= max_val: + return False + + # Recursively validate left and right subtrees + # Left subtree: all values must be < node.val + # Right subtree: all values must be > node.val + return (validate(node.left, min_val, node.val) and + validate(node.right, node.val, max_val)) + + return validate(root, float('-inf'), float('inf')) \ No newline at end of file