Tutorialspoint
Problem
Solution
Submissions

Binary Tree is a Valid BST

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

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. - Both the left and right subtrees must also be binary search trees.

Example 1
  • Input:

     Binary Tree with root node 2

  • Output: true
  • Explanation:
    • The binary tree has root value 2, left child with value 1, and right child with value 3.
    • This forms a valid BST.
Example 2
  • Input: 

    Binary Tree with root node 5

  • Output: false
  • Explanation:
    • The node with value 4 has a left child with value 3, which is valid.
    • However, it also has a right child with value 6, which is greater than the root value 5.
    • This violates the BST property.
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
  • Space Complexity: O(h), where h is the height of the tree
Binary TreeTreeShopifyArctwist
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 recursion to check each subtree.
  • Keep track of the valid range for each node.
  • Traverse the tree in-order and check if values are in ascending order.
  • Be careful about edge cases with duplicate values.

Steps to solve by this approach:

 Step 1: Use a recursive helper function that takes a node and the valid range for that node (min and max values).
 Step 2: If the node is null, return true (an empty tree is a valid BST).
 Step 3: Check if the current node's value is within the valid range. If not, return false.
 Step 4: Recursively check the left subtree, updating the max value to the current node's value.
 Step 5: Recursively check the right subtree, updating the min value to the current node's value.
 Step 6: Return true only if both the left and right subtrees are valid BSTs.
 Step 7: Use long.MinValue and long.MaxValue as the initial range to handle edge cases with integer boundaries.

Submitted Code :