Tutorialspoint
Problem
Solution
Submissions

Binary Search Tree

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

Write a Java program to determine if a given binary tree is a valid Binary Search Tree (BST). A valid BST is defined as follows:

  • All nodes in the left subtree of a node have values less than the node's value.
  • All nodes in the right subtree of a node have values greater than the node's value.
  • Both the left and right subtrees must also be valid binary search trees.
Example 1
  • Input:
    • Tree:

      Binary Search Tree Equally Balance

  • Output: true
  • Explanation:
    • Root value is 2.
    • Left child value is 1, which is less than 2. Valid.
    • Right child value is 3, which is greater than 2. Valid.
    • Both subtrees are also valid BSTs.
    • Therefore, the entire tree is a valid BST.
Example 2
  • Input:
    • Tree:

      Binary Search Tree Not Equally Balance

  • Output: false
  • Explanation:
    • Root value is 5.
    • Left child value is 1, which is less than 5. Valid.
    • Right child value is 4, which is less than 5. Invalid.
    • Check the subtree with root 4.
    • Left child of 4 is 3, which is less than 4. Valid.
    • Right child of 4 is 6, which is greater than 4 but also greater than the root 5. Invalid.
    • Therefore, the tree 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), where n is the number of nodes in the tree
  • Space Complexity: O(h), where h is the height of the tree (due to recursion stack)
TreeEYSamsung
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

  • Consider using an in-order traversal approach (left-root-right)
  • For a valid BST, in-order traversal should produce sorted values
  • Alternatively, check each node against valid value ranges
  • Use recursion to validate left and right subtrees
  • Handle edge cases such as empty trees or trees with duplicate values

Steps to solve by this approach:

 Step 1: Define a recursive validation function that takes a node and its valid range (lower and upper bounds).
 Step 2: If the node is null, return true (empty tree is valid).
 Step 3: Check if the node's value is within the valid range.
 Step 4: For the left subtree, the upper bound becomes the current node's value.
 Step 5: For the right subtree, the lower bound becomes the current node's value.
 Step 6: Recursively validate both subtrees and return true only if both are valid.
 Step 7: Handle edge cases like integer overflow by using Integer objects that can be null.

Submitted Code :