Skip to content

Instantly share code, notes, and snippets.

@kerbelp
Created March 25, 2017 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerbelp/a7f0615998b4e2149d19987466bb4692 to your computer and use it in GitHub Desktop.
Save kerbelp/a7f0615998b4e2149d19987466bb4692 to your computer and use it in GitHub Desktop.
validate bst
#!/usr/bin/env python
class Node:
def __init__(self, value):
self.value = value
self.right = None
self.left = None
def is_valid_bst(self, head=None):
if self.left is None:
return True
if self.right is None:
return True
if self.left.value >= self.value:
return False
if self.right.value <= self.value:
return False
if head and (self.left.value + self.right.value) > head:
return False
return self.left.is_valid_bst(self.value) and self.right.is_valid_bst(self.value)
def main():
a = Node(3)
b = Node(2)
a.left = b
c = Node(5)
a.right = c
d = Node(1)
b.left = d
e = Node(4)
b.right = e
print(a.is_valid_bst())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment