Validate Binary Search Tree - Python Solution

1. Introduction

The "Validate Binary Search Tree" problem is a classic question in tree-based algorithms, focusing on verifying the properties of a binary search tree (BST). A binary search tree has specific rules about the placement of nodes, making it efficient for search operations. This problem tests understanding of tree traversal and BST properties.

Problem

Given the root of a binary tree, the task is to determine if it is a valid binary search tree (BST). A BST is valid if the left subtree of a node contains only nodes with keys less than the node's key, the right subtree contains only nodes with keys greater than the node's key, and both the left and right subtrees must also be binary search trees.

2. Solution Steps

1. Utilize a recursive approach to validate each node.

2. Pass down the minimum and maximum values each node must adhere to.

3. Ensure each node's value is within the valid range.

4. Check recursively for every subtree adhering to BST rules.

5. Return true if all nodes satisfy the BST properties, false otherwise.

3. Code Program

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def isValidBST(root):
    def validate(node, low=float('-inf'), high=float('inf')):
        # An empty tree is a valid BST
        if not node:
            return True
        # Check if the node's value falls within the valid range
        if not (low < node.val < high):
            return False
        # Recursively validate the left and right subtree
        return (validate(node.left, low, node.val) and
                validate(node.right, node.val, high))

    return validate(root)

# Example Usage
root = TreeNode(2)
root.left = TreeNode(1)
root.right = TreeNode(3)
print(isValidBST(root))

root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(4, TreeNode(3), TreeNode(6))
print(isValidBST(root))

Output:

True
False

Explanation:

1. Recursive Validation: The validate function checks if a given node and its subtrees satisfy BST properties.

2. Valid Range: Each node must have a value greater than the allowed minimum and less than the allowed maximum.

3. Left and Right Subtrees: The function recursively checks the left subtree (values must be less than the node's value) and the right subtree (values must be greater).

4. Base Case: An empty node (base case of recursion) is considered a valid BST.

5. Overall Result: If all nodes in the tree satisfy the BST conditions, the function returns True; otherwise, it returns False.


Comments