
Problem
Solution
Submissions
Validate Binary Search Tree
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to determine if a given binary tree 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 1
- Input: root = [2,1,3]
- Output: true
- Explanation:
- The tree has root node with value 2.
- The left child has value 1, which is less than 2.
- The right child has value 3, which is greater than 2.
- Both subtrees are valid BSTs (single nodes).
- Therefore, this is a valid BST.
- The tree has root node with value 2.
Example 2
- Input: root = [5,1,4,null,null,3,6]
- Output: false
- Explanation:
- The tree has root node with value 5.
- The left subtree contains node 1, which is valid.
- The right subtree has root 4 with children 3 and 6.
- Node 3 is in the right subtree of 5, but 3 < 5, violating BST property.
- Therefore, this is not a valid BST.
- The tree has root node with value 5.
Constraints
- The number of nodes in the tree is in the range [1, 10^4]
- -2^31 ≤ Node.val ≤ 2^31 - 1
- Time Complexity: O(n)
- Space Complexity: O(n) for recursion stack
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use recursive approach with min and max bounds for each node
- For each node, check if its value is within the valid range
- Update the bounds when recursing: left subtree gets updated max, right subtree gets updated min
- The root node can have any value, so start with infinite bounds
- Return false immediately if any node violates the BST property