Tutorialspoint
Problem
Solution
Submissions

Valid Binary Search Tree

Certification: Advanced Level Accuracy: 62.5% Submissions: 8 Points: 15

Write a Python function that checks 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:

    Binary Search Tree One - Root node with value 2

  • Output: True
  • Explanation:
    • The tree has the following structure:
    • - Root node with value 2
    • - Left child with value 1 (less than 2)
    • - Right child with value 3 (greater than 2)
    • All BST properties are satisfied.
Example 2
  • Input:

    Binary Search Tree Two - Root node with value 5

  • Output: False
  • Explanation:
    • The tree has the following structure:
    • - Root node with value 5
    • - Left child with value 1 (less than 5)
    • - Right child with value 4 (less than 5, which violates BST property)
    • - Left child of 4 is 3 (less than 4)
    • - Right child of 4 is 6 (greater than 4)
    • The value 4 is not greater than 5, so this is not a valid BST.
Constraints
  • Number of nodes in the tree is in the range [1, 10^4]
  • -2^31 ≤ Node.val ≤ 2^31 - 1
  • Time Complexity: O(n), where n is the number of nodes
  • Space Complexity: O(h), where h is the height of the tree
RecursionBinary TreeGoogleTutorialspoint
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 inorder traversal and check if values are in ascending order
  • Use a recursive approach with min and max boundary values
  • Check each node's value against valid ranges
  • Handle edge cases like duplicates according to BST definition

Steps to solve by this approach:

 Step 1: Use recursive validation with min and max value constraints.

 Step 2: Initially set min value to negative infinity and max value to positive infinity.
 Step 3: Check if the current node's value is within the valid range.
 Step 4: For the left subtree, update the max constraint to the current node's value.
 Step 5: For the right subtree, update the min constraint to the current node's value.
 Step 6: Return true only if current node and all its subtrees satisfy BST properties.

Submitted Code :