blob: 4cf245e2c05e4e3c5f3eeeab4038125fef740b3f (
plain) (
blame)
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
|
#!/usr/bin/env python3
# not mine
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
"""dog-slow"""
def isValid(root, node_min, node_max):
if root is None:
return True
if node_min is not None and root.val <= node_min:
return False
if node_max is not None and root.val >= node_max:
return False
return isValid(root.left, node_min, root.val) and isValid(
root.right, root.val, node_max
)
return isValid(root, None, None)
def main():
node11 = TreeNode(2)
node12 = TreeNode(1)
node13 = TreeNode(3)
node11.left = node12
node11.right = node13
node21 = TreeNode(5)
node22 = TreeNode(1)
node23 = TreeNode(4)
node24 = TreeNode(3)
node25 = TreeNode(6)
node21.left = node22
node21.right = node23
node23.left = node24
node23.right = node25
node31 = TreeNode(5)
node32 = TreeNode(4)
node33 = TreeNode(6)
node34 = TreeNode(3)
node35 = TreeNode(7)
node31.left = node32
node31.right = node33
node33.left = node34
node33.right = node35
solution = Solution()
print(solution.isValidBST(node11))
print(solution.isValidBST(node21))
print(solution.isValidBST(node31))
if __name__ == "__main__":
main()
|