forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0098.py
45 lines (36 loc) · 1.07 KB
/
0098.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
# class Solution:
# def _isValidBST(self, root, left=None, right=None):
# if not root:
# return True
# if left and left.val >= root.val:
# return False
# if right and right.val <= root.val:
# return False
# return self._isValidBST(root.left, left, root) and self._isValidBST(root.right, root, right)
# def isValidBST(self, root):
# """
# :type root: TreeNode
# :rtype: bool
# """
# return self._isValidBST(root)
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
pre = None
stack = list()
while root or stack:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
if pre and root.val <= pre.val:
return False
pre = root
root = root.right
return True