To check if a binary tree satisfies the properties of a Binary Search Tree (BST), you need to ensure that for every node:
All values in its left subtree are strictly less than the node's value.
All values in its right subtree are strictly greater than the node's value.
The key challenge is that this property applies to all descendants, not just immediate children. A common and robust way to check this is to pass down a valid range (min and max values) that each node's value must fall within.
BST Definition Note: Some definitions allow duplicate values (e.g., left <= node < right or left < node <= right). This solution implements the more common "strict" BST definition where all values in the left subtree are strictly less and all values in the right subtree are strictly greater.
python
import math
class TreeNode:
"""
Represents a node in a binary tree.
"""
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def is_binary_search_tree(root):
"""
Checks if a given binary tree is a valid Binary Search Tree (BST).
Args:
root: The root node of the binary tree.
Returns:
True if the tree is a BST, False otherwise.
"""
# Use a helper function that can pass min and max bounds
# Initial bounds are effectively -infinity and +infinity
return _is_bst_helper(root, float('-inf'), float('inf'))
def _is_bst_helper(node, min_val, max_val):
"""
Recursive helper function to check BST properties.
Args:
node: The current node being checked.
min_val: The minimum allowed value for the current node and its subtree.
max_val: The maximum allowed value for the current node and its subtree.
Returns:
True if the subtree rooted at 'node' is a valid BST within the given bounds,
False otherwise.
"""
# Base Case 1: An empty tree is a valid BST.
if node is None:
return True
# Check if the current node's value is within the allowed range.
# For a strict BST, node.value must be strictly greater than min_val
# and strictly less than max_val.
if not (min_val < node.value < max_val):
return False
# Recursively check the left subtree:
# The new max_val for the left subtree is the current node's value.
# The min_val remains the same.
left_is_bst = _is_bst_helper(node.left, min_val, node.value)
# Recursively check the right subtree:
# The new min_val for the right subtree is the current node's value.
# The max_val remains the same.
right_is_bst = _is_bst_helper(node.right, node.value, max_val)
# If both left and right subtrees are valid BSTs, then the current
# subtree is also a valid BST.
return left_is_bst and right_is_bst
# --- Example Usage ---
# Example 1: Valid BST
# 4
# / \
# 2 5
# / \
# 1 3
root1 = TreeNode(4)
root1.left = TreeNode(2)
root1.right = TreeNode(5)
root1.left.left = TreeNode(1)
root1.left.right = TreeNode(3)
print(f"Tree 1 is BST: {is_binary_search_tree(root1)}") # Expected: True
# Example 2: Invalid BST (left child of 4 is 6, which is > 4)
# 4
# / \
# 6 5
root2 = TreeNode(4)
root2.left = TreeNode(6)
root2.right = TreeNode(5)
print(f"Tree 2 is BST: {is_binary_search_tree(root2)}") # Expected: False
# Example 3: Invalid BST (10 in left subtree of 7, but 10 > 5)
# 7
# / \
# 5 9
# /
# 10
root3 = TreeNode(7)
root3.left = TreeNode(5)
root3.right = TreeNode(9)
root3.left.left = TreeNode(10)
print(f"Tree 3 is BST: {is_binary_search_tree(root3)}") # Expected: False (because 10 is in 5's right subtree)
# Example 4: Single node tree
root4 = TreeNode(10)
print(f"Tree 4 is BST: {is_binary_search_tree(root4)}") # Expected: True
# Example 5: Empty tree
root5 = None
print(f"Tree 5 is BST: {is_binary_search_tree(root5)}") # Expected: True
# Example 6: More complex invalid case (3 is in the right subtree of 2, but also in the left subtree of 4)
# 4
# / \
# 2 6
# \
# 3
root6 = TreeNode(4)
root6.left = TreeNode(2)
root6.right = TreeNode(6)
root6.left.right = TreeNode(3)
print(f"Tree 6 is BST: {is_binary_search_tree(root6)}") # Expected: True (This is a valid BST for the given definition!)
# Correction for Example 6: Let's make an invalid one
# 4
# / \
# 2 6
# \
# 5 (Invalid because 5 is in the left subtree of 4 but 5 > 4)
root7 = TreeNode(4)
root7.left = TreeNode(2)
root7.right = TreeNode(6)
root7.left.right = TreeNode(5)
print(f"Tree 7 is BST: {is_binary_search_tree(root7)}") # Expected: False (5 violates rule for node 4)
Explanation:
TreeNode Class: A simple class to define the structure of each node in the binary tree, holding its value and references to its left and right children.
is_binary_search_tree(root) (Wrapper Function):
This is the main function that you'll call.
It initializes the recursive process by calling the helper function _is_bst_helper.
The initial min_val is float('-inf') (negative infinity) and max_val is float('inf') (positive infinity). This ensures that the very first node (the root) can have any value, as long as its children respect the BST properties relative to it.
If we reach an empty spot (a null child), that's a valid "empty" BST, so we return True. This is the termination condition for the recursion.
Check Current Node's Value:
if not (min_val < node.value < max_val): return False
This is the core check. It verifies if the node.value falls within the allowed range (min_val and max_val) inherited from its ancestors. If it doesn't, the tree is not a BST, and we immediately return False.
Recursive Calls:
Left Subtree:_is_bst_helper(node.left, min_val, node.value)
When moving to the left child, the new max_val becomes the node.value itself. This is because all nodes in the left subtree must be strictly less than the current node.value. The min_val remains the same as it was for the current node.
Right Subtree:_is_bst_helper(node.right, node.value, max_val)
When moving to the right child, the new min_val becomes the node.value itself. This is because all nodes in the right subtree must be strictly greater than the current node.value. The max_val remains the same.
This approach efficiently checks all nodes and their relationships to their ancestors by maintaining the valid range of values at each step of the recursion.
Combine Results:return left_is_bst and right_is_bst
For the current subtree to be a valid BST, both its left and its right subtrees must also be valid BSTs. If either recursive call returns False, this function will also return False.