Validate Binary Search Tree
Examples
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [1,2,3]
Output: false
Explanation:
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [1,2,3]
Output: false
Explanation:
Given the root of a binary tree, return true if it is a valid binary search tree, otherwise return false.
A valid binary search tree satisfies the following constraints:
The root node's value is 1 but its left child's value is 2 which is greater than 1.
1 <= The number of nodes in the tree <= 1000-1000 <= Node.val <= 1000Validate the tree with DFS and value bounds. Each node must be strictly greater than all values in its left subtree and strictly less than all values in its right subtree, so pass down (low, high) limits during recursion. An empty tree is valid.
The BST property is global, not just local to children. Maintaining bounds ensures every node respects the constraints imposed by all its ancestors. If any node violates the range, the tree is invalid; otherwise it is valid.
O(n)O(h)class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def dfs(node: Optional[TreeNode], low: float, high: float) -> bool:
if not node:
return True
if not (low < node.val < high):
return False
return dfs(node.left, low, node.val) and dfs(node.right, node.val, high)
return dfs(root, float('-inf'), float('inf'))