forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_bst.py
More file actions
25 lines (19 loc) · 818 Bytes
/
validate_bst.py
File metadata and controls
25 lines (19 loc) · 818 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from typing import Optional
from tree_node import Node
def is_valid_bst(
root: Optional[Node], min_node: Optional[Node], max_node: Optional[Node]
) -> bool:
"""Function to check if a binary tree is a binary search tree"""
# If the tree is empty, return True
if root is None:
return True
# If the root value is less than or equal to the minimum value, return False
if min_node is not None and root.data <= min_node.data:
return False
# If the root value is greater than or equal to the maximum value, return False
if max_node is not None and root.data >= max_node.data:
return False
# Recursively check if the left and right subtrees are BSTs
return is_valid_bst(root.left, min_node, root) and is_valid_bst(
root.right, root, max_node
)