98. Validate Binary Search Tree
Memoization, Math, DP, Review ·Problem Statement
link: https://leetcode.com/problems/validate-binary-search-tree/ https://leetcode.cn/problems/validate-binary-search-tree/
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. Both the left and right subtrees must also be binary search trees.
Example:
Input: root = [2,1,3]
Output: true
Input: root = [5,1,4,null,null,3,6]
Output: false
Solution Approach
The solution utilizes a recursive approach, ensuring that every node’s value in the tree lies within the permitted range defined by its ancestors.
Algorithm
- A recursive function, check, evaluates whether each node lies within a specific value range.
- For each node, it confirms the node’s value is within its allowed range and then recursively checks its children, updating the range accordingly.
- The tree is deemed valid if all nodes adhere to BST conditions; otherwise, it’s invalid.
Implement
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def check(root, l, r):
if root == None:
return True
val = root.val
if val <= l or val >= r:
return False
return check(root.left,l, root.val) and check(root.right, root.val, r)
return check(root, float('-inf'), float('inf'))