This repository has been archived by the owner on Jul 30, 2020. It is now read-only.
forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path98_Validate_Binary_Search_Tree.py
72 lines (58 loc) · 2.16 KB
/
98_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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BST:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Average: O(log(n)) time | O(1) space
# Worst: O(n) time | O(1) space
def insert(self, val):
currentNode = self
while True:
if val < currentNode.val:
if currentNode.left is None:
currentNode.left = BST(val)
break
else:
currentNode = currentNode.left
else:
if currentNode.right is None:
currentNode.right = BST(val)
break
else:
currentNode = currentNode.right
return self
import sys
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
MAX = sys.maxint
MIN = -sys.maxint - 1
return self.isValidBSTHelper(root, MIN, MAX)
def isValidBSTHelper(self, root, minValue, maxValue):
if root is None:
return True
if root.left is None and root.right is None:
return minValue < root.val < maxValue
if root.val <= minValue or root.val >= maxValue:
return False
leftSubtreeIsValid = self.isValidBSTHelper(root.left, minValue, root.val)
rightSubtreeIsValid = self.isValidBSTHelper(root.right, root.val, maxValue)
return leftSubtreeIsValid and rightSubtreeIsValid
# driver/test code
# test_tree = BST(100).insert(5).insert(15).insert(5).insert(2).insert(1).insert(22) \
# .insert(1).insert(1).insert(3).insert(1).insert(1).insert(502).insert(55000) \
# .insert(204).insert(205).insert(207).insert(206).insert(208).insert(203) \
# .insert(-51).insert(-403).insert(1001).insert(57).insert(60).insert(4500)
test_tree = BST(2).insert(1).insert(4).insert(None).insert(None).insert(3).insert(6)
sol = Solution()
is_valid_bst = sol.isValidBST(test_tree)
print("Is BST valid ? - ", is_valid_bst)