Refactor existing bst-checker implementation
I believe the previous solution is invalid. This solution works and it should be more time and space efficient. Space-wise our stack grows proportionate to the depth of our tree, which for a "balanced" BST should be log(n). Doing a BFT on a BST results in memory usage of n because when we encounter the leaf nodes at the final level in the tree, they will be 1/2 * n for a balanced BST.
This commit is contained in:
parent
1dc6695a47
commit
2b5bbb98ca
1 changed files with 10 additions and 40 deletions
|
@ -6,47 +6,17 @@ class Node(object):
|
||||||
self.left = left
|
self.left = left
|
||||||
self.right = right
|
self.right = right
|
||||||
|
|
||||||
def insert_left(self, value):
|
|
||||||
self.left = Node(value)
|
|
||||||
return self.left
|
|
||||||
|
|
||||||
def insert_right(self, value):
|
|
||||||
self.right = Node(value)
|
|
||||||
return self.right
|
|
||||||
|
|
||||||
def min(self):
|
|
||||||
xs = deque()
|
|
||||||
result = float('inf')
|
|
||||||
xs.append(self)
|
|
||||||
while xs:
|
|
||||||
node = xs.popleft()
|
|
||||||
result = min(result, node.value)
|
|
||||||
if node.left:
|
|
||||||
xs.append(node.left)
|
|
||||||
if node.right:
|
|
||||||
xs.append(node.right)
|
|
||||||
return result
|
|
||||||
|
|
||||||
def max(self):
|
|
||||||
xs = deque()
|
|
||||||
result = float('-inf')
|
|
||||||
xs.append(self)
|
|
||||||
while xs:
|
|
||||||
node = xs.popleft()
|
|
||||||
result = max(result, node.value)
|
|
||||||
if node.left:
|
|
||||||
xs.append(node.left)
|
|
||||||
if node.right:
|
|
||||||
xs.append(node.right)
|
|
||||||
return result
|
|
||||||
|
|
||||||
def is_bst(self):
|
def is_bst(self):
|
||||||
result = True
|
s = []
|
||||||
if self.left:
|
s.append((float('-inf'), self, float('inf')))
|
||||||
result = result and self.left.max() < self.value
|
while s:
|
||||||
if self.right:
|
lo, node, hi = s.pop()
|
||||||
result = result and self.right.min() > self.value
|
if lo <= node.value <= hi:
|
||||||
return result
|
node.left and s.append((lo, node.left, node.value))
|
||||||
|
node.right and s.append((node.value, node.right, hi))
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
x = Node(
|
x = Node(
|
||||||
|
|
Loading…
Reference in a new issue