Function to check if a binary tree is a binary search tree
(
root: Optional[Node], min_node: Optional[Node], max_node: Optional[Node]
)
| 3 | |
| 4 | |
| 5 | def is_valid_bst( |
| 6 | root: Optional[Node], min_node: Optional[Node], max_node: Optional[Node] |
| 7 | ) -> bool: |
| 8 | """Function to check if a binary tree is a binary search tree""" |
| 9 | |
| 10 | # If the tree is empty, return True |
| 11 | if root is None: |
| 12 | return True |
| 13 | |
| 14 | # If the root value is less than or equal to the minimum value, return False |
| 15 | if min_node is not None and root.data <= min_node.data: |
| 16 | return False |
| 17 | |
| 18 | # If the root value is greater than or equal to the maximum value, return False |
| 19 | if max_node is not None and root.data >= max_node.data: |
| 20 | return False |
| 21 | |
| 22 | # Recursively check if the left and right subtrees are BSTs |
| 23 | return is_valid_bst(root.left, min_node, root) and is_valid_bst( |
| 24 | root.right, root, max_node |
| 25 | ) |