-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidateBST.py
More file actions
40 lines (29 loc) · 822 Bytes
/
ValidateBST.py
File metadata and controls
40 lines (29 loc) · 822 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Created by Elshad Karimov
# Copyright © AppMillers. All rights reserved.
# Validate BST
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def helper(node, minValue = float('-inf'), maxValue = float('inf')):
if not node:
return True
val = node.val
if val <= minValue or val >= maxValue:
return False
if not helper(node.right, val, maxValue):
return False
if not helper(node.left, minValue, val):
return False
return True
def isValidBST(root):
return helper(root)
root1 = TreeNode(2)
root1.left = TreeNode(1)
root1.right = TreeNode(4)
print(isValidBST(root1))
root2 = TreeNode(4)
root2.left = TreeNode(1)
root2.right = TreeNode(3)
print(isValidBST(root2))