-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path98.py
48 lines (44 loc) · 1.59 KB
/
98.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
__________________________________________________________________________________________________
sample 36 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not root:
return True
def checkBST(node, left, right):
if node.val >= right or node.val <= left:
return False
if node.left:
if not checkBST(node.left, left, node.val):
return False
if node.right:
if not checkBST(node.right, node.val, right):
return False
return True
return checkBST(root, -float('inf'), float('inf'))
__________________________________________________________________________________________________
sample 15472 kb submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
pre, cur, stack = None, root, []
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
s = stack.pop()
if pre and s.val <= pre.val:
return False
pre, cur = s, s.right
return True
__________________________________________________________________________________________________