Validate a Binary Search Tree
Check that every node fits strictly inside the range its ancestors allow.
The problem
Implement Solution.isValidBST(root). root is the root TreeNode of a binary tree (each node has val, left and right), or None for an empty tree. Return True if the tree is a valid binary search tree: for every node, every value in its left subtree is strictly smaller than the node's value and every value in its right subtree is strictly larger. Equal values are not allowed. An empty tree is valid. Trees are written in level order with None for a missing child. [2, 1, 3] is valid. [8, 3, 10, 1, 9] is not: 9 is a fine right child of 3, but it sits in the left subtree of 8 and is larger than 8. Constraints: the tree has 0 to 10,000 nodes; values fit in a signed 32-bit integer, so they can be exactly -2147483648 or 2147483647. Return a bool and do not change the tree.
Starter code
class Solution:
def isValidBST(self, root):
passPublic examples
root = [2, 1, 3]givesTrueroot = [-7]givesTrueroot = [-2147483648, None, 2147483647]givesTrue
Solving it in the practice book needs an active paid plan.
Open it in the practice book