Skip to content

Instantly share code, notes, and snippets.

@messa
Last active April 21, 2017 20:33
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 messa/18cbc0ff07f28ede7cc654ca5edbfd30 to your computer and use it in GitHub Desktop.
Save messa/18cbc0ff07f28ede7cc654ca5edbfd30 to your computer and use it in GitHub Desktop.
Check whether Binary Tree is a Binary Search Tree
# from HackerRank.com
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_binary_search_tree_(root, lower_bound=None, upper_bound=None):
if not root:
return True
if lower_bound is not None and root.data <= lower_bound:
return False
if upper_bound is not None and root.data >= upper_bound:
return False
if not check_binary_search_tree_(root.left, lower_bound, root.data):
return False
if not check_binary_search_tree_(root.right, root.data, upper_bound):
return False
if root.left and root.left.data >= root.data:
return False
if root.right and root.right.data <= root.data:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment