1+ Given the root of a binary tree , determine if it is a valid binary search tree (BST ).
2+
3+ A valid BST is defined as follows :
4+
5+ The left subtree of a node contains only nodes with keys less than the node - s key .
6+ The right subtree of a node contains only nodes with keys greater than the node - s key .
7+ Both the left and right subtrees must also be binary search trees .
8+
9+
10+ Example 1 :
11+ Input : root = [2 ,1 ,3 ]
12+ Output : true
13+
14+ Example 2 :
15+ Input : root = [5 ,1 ,4 ,null ,null ,3 ,6 ]
16+ Output : false
17+ Explanation : The root node - s value is 5 but its right child - s value is 4.
18+
19+
20+ Constraints :
21+ The number of nodes in the tree is in the range [1 , 104 ].
22+ - 231 <= Node .val <= 231 - 1
23+
24+
25+ # Definition for a binary tree node.
26+ # class TreeNode:
27+ # def __init__(self, val=0, left=None, right=None):
28+ # self.val = val
29+ # self.left = left
30+ # self.right = right
31+
32+ # O(n) Time and O(n) Space
33+ class Solution :
34+ def isValidBST (self , root : TreeNode ) -> bool :
35+
36+
37+ return self .helper (root , None , None )
38+
39+ def helper (self , node , max_val , min_val ):
40+
41+ if node is None :
42+ return True
43+
44+
45+ if (max_val is not None and node .val >= max_val ) or (min_val is not None and node .val <= min_val ):
46+ return False
47+
48+ else :
49+ return self .helper (node .left , node .val , min_val ) and self .helper (node .right , max_val , node .val )
50+
51+
52+ # Alternate Solution
53+ class Solution :
54+ def isValidBST (self , root : TreeNode ) -> bool :
55+ if not root :
56+ return True
57+
58+ stack = [(root , - math .inf , math .inf )]
59+
60+ while stack :
61+ root , lower , upper = stack .pop ()
62+
63+ if not root :
64+ continue
65+
66+ val = root .val
67+
68+ if val <= lower or val >= upper :
69+ return False
70+
71+
72+ stack .append ((root .right , val , upper ))
73+ stack .append ((root .left , lower , val ))
74+
75+
76+ return True
0 commit comments