forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate-binary-search-tree.py
More file actions
74 lines (62 loc) · 2.24 KB
/
validate-binary-search-tree.py
File metadata and controls
74 lines (62 loc) · 2.24 KB
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
73
74
"""
1.
for recursive/iterative solution
if you are a left node
your max will be your parent's value
your min will be yout parent's min, because your parent might be someone's right child.
if you are a right node
your min will be your parent's value
your max will be your parent's max, because your parent might be someone's left child.
root have no max and min
2.
for in-order traversal solution
if you use in-order to traverse a BST
the value you list out will be in order(sorted)
so each element would be greater than the last one
in-order traverse:
left child -> current node -> right child
normaly I will recursivly do the in-order traversing
but iterative is easier to track the last element'value
3. I personally like in-order traversal solution
"""
class Solution(object):
#recursive
def isValidBST(self, root):
def helper(node, min_val, max_val):
if node==None:
return True
if node.val<=min_val or node.val>=max_val:
return False
left_valid = helper(node.left, min_val, node.val)
if not left_valid: return False
right_valid = helper(node.right, node.val, max_val)
if not right_valid: return False
return True
return helper(root, float('-inf'), float('inf'))
#iterative
def isValidBST(self, root):
if root==None: return True
stack = [(root, float('-inf'), float('inf'))]
while stack:
node, min_val, max_val = stack.pop()
if node.val<=min_val or node.val>=max_val:
return False
if node.left:
stack.append((node.left, min_val, node.val))
if node.right:
stack.append((node.right, node.val, max_val))
return True
#in-order traversal
def isValidBST(self, root):
stack = []
last_val = float('-inf')
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if root.val<=last_val:
return False
last_val = root.val
root = root.right #if root.right: root = root.right
return True