- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidate_binary_search_tree.py
36 lines (27 loc) · 990 Bytes
/
validate_binary_search_tree.py
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
26
27
28
29
30
31
32
33
34
35
36
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# define a method to test if it is a BST
defBST_valid(root, min_value, max_value):
# not a TreeNode
ifnotroot:
returnTrue
# the cases: not a BST
if (root.val>=max_value) or (root.val<=min_value):
returnFalse
# test the left node
left_test=BST_valid( root.left, min_value, root.val)
# test the right node
right_test=BST_valid( root.right, root.val, max_value)
# return the result
return (left_testandright_test)
classSolution:
defisValidBST(self, root: TreeNode) ->bool:
# initialize the max and min values
max_inf=float('inf')
min_inf=float('-inf')
# recursive test
returnBST_valid(root, min_inf, max_inf)