Tutorialspoint
Problem
Solution
Submissions

Validate Binary Search Tree

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C 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, and both the left and right subtrees must also be binary search trees.

Example 1
  • Input: Tree structure [2,1,3]
  • Output: true
  • Explanation:
    • Root node is 2, left child is 1, right child is 3.
    • Left subtree contains only values less than 2 (which is 1).
    • Right subtree contains only values greater than 2 (which is 3).
    • Therefore, this is a valid BST.
Example 2
  • Input: Tree structure [5,1,4,null,null,3,6]
  • Output: false
  • Explanation:
    • Root node is 5, left child is 1, right child is 4.
    • The right subtree has root 4, which is less than 5 (valid so far).
    • Node 4 has left child 3 and right child 6.
    • Node 3 is in the right subtree of root 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
  • You must validate the entire tree structure
  • Time Complexity: O(n)
  • Space Complexity: O(h) where h is the height of the tree
TreeGoldman SachsPhillips
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 in-order traversal to check if the values are in ascending order
  • Alternatively, use a recursive approach with min and max bounds
  • For each node, check if its value is within the valid range
  • Update the range for left and right subtrees accordingly
  • The left subtree should have values less than current node
  • The right subtree should have values greater than current node

Steps to solve by this approach:

 Step 1: Define a helper function that takes a node and its valid range (min, max).
 Step 2: Check if the current node is NULL (base case - return true).
 Step 3: Validate if the current node's value is within the valid range.
 Step 4: If invalid, return false immediately.
 Step 5: Recursively validate the left subtree with updated max bound (current node's value).
 Step 6: Recursively validate the right subtree with updated min bound (current node's value).
 Step 7: Return true only if both left and right subtrees are valid BSTs.

Submitted Code :