📘
Validate Binary Search Tree
MediumTrees
Given the root of a binary tree (as a level-order array), determine if it is a valid binary search tree (BST).
A valid BST has:
- Left subtree contains only nodes with keys less than the node's key
- Right subtree contains only nodes with keys greater than the node's key
- Both subtrees must also be valid BSTs
Example:
Input:
2,1,3
Output:
True
Reasoning:
- The input array
2,1,3represents a binary tree with root node2, left child1, and right child3. - We check the left subtree: since
1is less than2, it satisfies the BST condition. - We check the right subtree: since
3is greater than2, it satisfies the BST condition. - Both subtrees are valid BSTs (as they are single nodes with no children), so the entire tree is a valid binary search tree, resulting in an output of
True.
Constraints:
- 1 <= number of nodes <= 10^4
- -2^31 <= Node.val <= 2^31 - 1
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.