mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update bst_is_valid.py
This commit is contained in:
parent
f8dc224ae5
commit
e0ef50da5b
@ -3,26 +3,14 @@
|
|||||||
# author: bt3gl
|
# author: bt3gl
|
||||||
|
|
||||||
|
|
||||||
def is_valid_bst_recursive(root):
|
|
||||||
|
|
||||||
def is_valid(root, min_val=float(-inf), max_val=float(inf)):
|
|
||||||
if root is None:
|
|
||||||
return True
|
|
||||||
|
|
||||||
return (min_val < root.val < max_val) and \
|
|
||||||
is_valid(root.left, min_val, root.val) and \
|
|
||||||
is_valid(root.right, root.val, max_val)
|
|
||||||
|
|
||||||
return is_valid(root)
|
|
||||||
|
|
||||||
|
|
||||||
def is_valid_bst_iterative(root):
|
def is_valid_bst_iterative(root):
|
||||||
|
|
||||||
queue = deque()
|
queue = deque((root, float(-inf), float(inf)))
|
||||||
queue.append((root, float(-inf), float(inf)))
|
|
||||||
|
|
||||||
while queue:
|
while queue:
|
||||||
|
|
||||||
node, min_val, max_val = queue.popleft()
|
node, min_val, max_val = queue.popleft()
|
||||||
|
|
||||||
if node:
|
if node:
|
||||||
if min_val >= node.val or node.val >= max_val:
|
if min_val >= node.val or node.val >= max_val:
|
||||||
return False
|
return False
|
||||||
@ -34,6 +22,16 @@ def is_valid_bst_iterative(root):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_bst_recursive(root, min_val=float(-inf), max_val=float(inf)):
|
||||||
|
|
||||||
|
if root is None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return (min_val < root.val < max_val) and \
|
||||||
|
is_valid_bst_recursive(root.left, min_val, root.val) and \
|
||||||
|
is_valid_bst_recursive(root.right, root.val, max_val)
|
||||||
|
|
||||||
|
|
||||||
def is_valid_bst_inorder(root):
|
def is_valid_bst_inorder(root):
|
||||||
|
|
||||||
def inorder(node):
|
def inorder(node):
|
||||||
@ -41,14 +39,14 @@ def is_valid_bst_inorder(root):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
inorder(node.left)
|
inorder(node.left)
|
||||||
queue.append(node.val)
|
stack.append(node.val)
|
||||||
inorder(node.right)
|
inorder(node.right)
|
||||||
|
|
||||||
queue = []
|
stack = []
|
||||||
inorder(root)
|
inorder(root)
|
||||||
for i in range(1, len(queue)):
|
|
||||||
if queue[i] <= queue[i-1]:
|
for i in range(1, len(stack)):
|
||||||
|
if queue[i] <= queue[i - 1]:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user