diff --git a/trees/bst_is_valid.py b/trees/bst_is_valid.py index ec7a1dc..ebf356e 100644 --- a/trees/bst_is_valid.py +++ b/trees/bst_is_valid.py @@ -3,26 +3,14 @@ # 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): - queue = deque() - queue.append((root, float(-inf), float(inf))) + queue = deque((root, float(-inf), float(inf))) while queue: + node, min_val, max_val = queue.popleft() + if node: if min_val >= node.val or node.val >= max_val: return False @@ -32,6 +20,16 @@ def is_valid_bst_iterative(root): queue.append((node.right, node.val, max_val)) 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): @@ -41,14 +39,14 @@ def is_valid_bst_inorder(root): return True inorder(node.left) - queue.append(node.val) + stack.append(node.val) inorder(node.right) - queue = [] + stack = [] 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 True -