-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.py
More file actions
51 lines (36 loc) · 1016 Bytes
/
Copy pathBST.py
File metadata and controls
51 lines (36 loc) · 1016 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
41
42
43
44
45
46
47
48
49
50
51
# 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):
def helper(node, lower, upper):
if not node:
return True
val = node.val
if val <= lower or val >= upper:
return False
if not helper(node.right, val, upper):
return False
if not helper(node.left, lower, val):
return False
return True
return helper(root, float('-inf'), float('inf'))
node = TreeNode(5)
node.left = TreeNode(4)
node.right = TreeNode(7)
print(Solution().isValidBST(node))
# True
"""
class Solution:
def isValidBST(self, root):
def helper(node, left ,right):
if not node:
return True
if not left < val < right:
return False
return helper(node.left, left, node.val) and helper(node.right, node.val, right)
return helper(root, float("-inf"), float("inf"))
"""