Skip to content

Commit

Permalink
Fix a bug in binary search tree check
Browse files Browse the repository at this point in the history
  • Loading branch information
joowani committed Sep 20, 2017
1 parent 32d87ce commit 32bf26a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
27 changes: 21 additions & 6 deletions binarytree/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,31 @@ def _is_balanced(node):
return 0

left = _is_balanced(_left_of(node))
right = _is_balanced(_right_of(node))
if left < 0:
return -1

if left < 0 or right < 0 or abs(left - right) > 1:
right = _is_balanced(_right_of(node))
if right < 0 or abs(left - right) > 1:
return -1

return max(left, right) + 1


def _is_bst(node, min_val=float('-inf'), max_val=float('inf')):
"""Return True if and only if the tree is a binary search tree."""
if node == _null:
return True

if (min_val != _null and _value_of(node) <= min_val):
return False

if (max_val != _null and _value_of(node) >= max_val):
return False

return _is_bst(_left_of(node), min_val, _value_of(node)) and \
_is_bst(_right_of(node), _value_of(node), max_val)


def _build_list(root):
"""Build a list from a tree and return it."""
result = []
Expand Down Expand Up @@ -643,7 +661,6 @@ def inspect(bt):
bt = _prepare_tree(bt)

is_full = True
is_bst = True
is_descending = True
is_ascending = True
is_left_padded = True
Expand Down Expand Up @@ -685,7 +702,6 @@ def inspect(bt):
if left_child != _null:
if _value_of(left_child) > node_value:
is_descending = False
is_bst = False
elif _value_of(left_child) < node_value:
is_ascending = False
next_nodes.append(left_child)
Expand All @@ -696,7 +712,6 @@ def inspect(bt):
is_descending = False
elif _value_of(right_child) < node_value:
is_ascending = False
is_bst = False
next_nodes.append(right_child)
num_of_children += 1
if num_of_children == 1:
Expand All @@ -711,7 +726,7 @@ def inspect(bt):
'is_weight_balanced': is_balanced,
'is_max_heap': is_descending and is_left_padded and is_balanced,
'is_min_heap': is_ascending and is_left_padded and is_balanced,
'is_bst': is_bst,
'is_bst': _is_bst(bt),
'height': current_depth,
'leaf_count': leaf_count,
'node_count': node_count,
Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
setup(
name='binarytree',
description='Python Library for Learning Binary Trees',
version='2.0.0',
version='2.0.1',
author='Joohwan Oh',
author_email='joohwan.oh@outlook.com',
url='https://github.com/joowani/binarytree',
packages=find_packages(),
include_package_data=True,
tests_require=['pytest'],
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
Expand Down

0 comments on commit 32bf26a

Please sign in to comment.