Tutorialspoint
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.
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.
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
RecursionTreePwCD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a helper function that takes node, minimum bound, and maximum bound as parameters.
 Step 2: Handle base case - if node is null, return true (empty tree is valid BST).
 Step 3: Check if current node's value violates the min/max bounds, return false if so.
 Step 4: Recursively validate left subtree with updated maximum bound (current node's value).
 Step 5: Recursively validate right subtree with updated minimum bound (current node's value).
 Step 6: Return true only if both left and right subtrees are valid BSTs.
 Step 7: Start the validation with infinite bounds for the root node.

Submitted Code :