-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_bst.py
More file actions
28 lines (21 loc) · 789 Bytes
/
validate_bst.py
File metadata and controls
28 lines (21 loc) · 789 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
# 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):
if not root:
return True
smallest, largest = float("-inf"), float("inf")
stack = [(root, smallest, largest)]
while stack:
node, min_val, max_val = stack.pop()
if not (min_val < node.val < max_val):
return False
stack.append((node.right, node.val, max_val)) if node.right else None
stack.append((node.left, min_val, node.val)) if node.left else None
return True
# Time Complexity: O(n)
# Space Complexity: O(h)