1+ '''
2+ Valid binary search tree
3+
4+ Check if a given tree is a valid binary search tree.
5+
6+ Input: 5
7+ / \
8+ 1 7
9+ / \
10+ 6 8
11+ Output: True
12+
13+ =========================================
14+ Visit all nodes and check if the values are inside the boundaries.
15+ When visiting the left child use the value of the parent node like an upper boundary.
16+ When visiting the right child use the value of the parent node like a lower boundary.
17+ Time Complexity: O(N)
18+ Space Complexity: O(N) - (recursion is used, this complexity is because of stack)
19+ '''
20+
21+ ############
22+ # Solution #
23+ ############
24+
25+ import math
26+
27+ class TreeNode :
28+ def __init__ (self , val , left = None , right = None ):
29+ self .val = val
30+ self .left = left
31+ self .right = right
32+
33+ def is_valid_bst (root ):
34+ return is_valid_sub_bst (root , - math .inf , math .inf )
35+
36+ def is_valid_sub_bst (node , lower , upper ):
37+ if node is None :
38+ return True
39+
40+ if (node .val <= lower ) or (node .val >= upper ):
41+ return False
42+
43+ # check left
44+ if not is_valid_sub_bst (node .left , lower , node .val ):
45+ return False
46+
47+ # check right
48+ if not is_valid_sub_bst (node .right , node .val , upper ):
49+ return False
50+
51+ return True
52+
53+
54+ ###########
55+ # Testing #
56+ ###########
57+
58+ # Test 1
59+ '''
60+ 5
61+ / \
62+ 1 4
63+ / \
64+ 3 6
65+ '''
66+ # Correct result => False
67+ root = TreeNode (5 , TreeNode (1 ), TreeNode (4 , TreeNode (3 ), TreeNode (6 )))
68+ print (is_valid_bst (root ))
69+
70+ # Test 2
71+ '''
72+ 5
73+ / \
74+ 1 6
75+ / \
76+ 4 7
77+ '''
78+ # Correct result => False
79+ root = TreeNode (5 , TreeNode (1 ), TreeNode (6 , TreeNode (4 ), TreeNode (7 )))
80+ print (is_valid_bst (root ))
81+
82+ # Test 3
83+ '''
84+ 5
85+ / \
86+ 1 6
87+ / \
88+ 7 8
89+ '''
90+ # Correct result => False
91+ root = TreeNode (5 , TreeNode (1 ), TreeNode (6 , TreeNode (7 ), TreeNode (8 )))
92+ print (is_valid_bst (root ))
93+
94+ # Test 4
95+ '''
96+ 5
97+ / \
98+ 1 7
99+ / \
100+ 6 8
101+ '''
102+ # Correct result => True
103+ root = TreeNode (5 , TreeNode (1 ), TreeNode (7 , TreeNode (6 ), TreeNode (8 )))
104+ print (is_valid_bst (root ))
0 commit comments