Skip to main content

Validate Binary Search Tree


Validate Binary Search Tree: Given the root of a binary tree, determine if it 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:

image

Input: root = [2,1,3]
Output: true

Example 2:

image

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

Constraints:
  • The number of nodes in the tree is in the range [1, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1

Try this Problem on your own or check similar problems:

  1. Binary Tree Inorder Traversal
  2. Find Mode in Binary Search Tree
Solution:
class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, null, null);
}

private boolean helper(TreeNode root, Integer minimumValue, Integer maximumValue){
if(root == null) return true;
if((minimumValue != null && root.val <= minimumValue) || (maximumValue != null && root.val >= maximumValue)) return false;

return helper(root.left, minimumValue, root.val) && helper(root.right, root.val, maximumValue);
}
}

Time/Space Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Explanation:

The recursive algorithm is actually explained by the problem statement, we check if the root val is in boundary and then check both left and right subtree passing the right boundaries to helper function (for left subtree, we know the maximum value can be that of the root, while for the right subtree we know that the minimum value must be the root value). We pass null as the initial value for minimumValue and maximumValue since node values can be Integer.MIN_VALUE = -2^31 or Integer.MAX_VALUE = 2^31 - 1, and we do the additional guard check for null value when checking the boundaries. The solution yields a linear space and time complexity (since for space we have a recursions stack for right and left skewed trees).