Given the root of a binary tree, determine whether it is a valid binary search tree (BST).
A valid BST must satisfy these conditions:
-
The left subtree of a node contains only nodes with values less than the node's value.
-
The right subtree of a node contains only nodes with values greater than the node's value.
-
Both the left and right subtrees must also be valid binary search trees.
Return True if the tree is a valid BST and False otherwise.
Function Signature
from typing import Optional
def is_valid_bst(root: Optional[TreeNode]) -> bool:
Rules
-
root
is a
TreeNode
with fields
val
,
left
and
right
. A missing child is
None
.
-
The examples write the tree as a level-order list, with
None
marking a missing child.
-
Conditions 1 and 2 apply to every node in the subtree, not only to the direct children.
-
Both comparisons are strict. A node whose value equals an ancestor's value makes the tree invalid, on either side.
Constraints
-
1 <= number of nodes in the tree <= 10^4
-
-10^4 <= Node.val <= 10^4
Examples
Example 1
Input: root = [3, 2, 5]
Output: True
The root 3 has left child 2 and right child 5. Both children are leaves and 2 < 3 < 5, so every condition holds.
Example 2
Input: root = [10, 5, 15, None, None, 8, 20]
Output: False
Node 15 has children 8 and 20, which is fine for node 15 alone. But 8 is in the right subtree of the root 10 and is smaller than 10, so condition 2 fails at the root.
Example 3
Input: root = [2, 2, 3]
Output: False
The left child has the same value as the root. The left subtree may only hold values strictly less than 2, so the tree is not a valid BST.