Validate BST
Detailed guide and Python implementation for the 'Validate BST' problem.
Problem Statement
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 strictly less than the node's key.
- The right subtree of a node contains only nodes with keys strictly greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
The tree is represented as a level-order list. Implement a function isValidBST(root: list) -> bool.
- •The number of nodes in the tree is in the range [1, 10000]
- •-2^31 <= Node.val <= 2^31 - 1
Examples
[2,1,3]
True
The left child 1 < root 2, and right child 3 > root 2. Valid BST.
[5,1,4,None,None,3,6]
False
The right child of root is 4, which is less than 5. Also, node 3 is in the right subtree of 5 but is less than 5. Not a valid BST.
[5,4,6,None,None,3,7]
False
Node 3 is in the right subtree of 5 but has value 3 < 5. Not valid.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.