From 32bf26a1e49616fd6180aee8097d3eb24d1ddfce Mon Sep 17 00:00:00 2001 From: Joohwan Oh Date: Tue, 19 Sep 2017 21:51:21 -0700 Subject: [PATCH] Fix a bug in binary search tree check --- binarytree/__init__.py | 27 +++++++++++++++++++++------ setup.py | 3 ++- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/binarytree/__init__.py b/binarytree/__init__.py index 426ca40..7546c77 100644 --- a/binarytree/__init__.py +++ b/binarytree/__init__.py @@ -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 = [] @@ -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 @@ -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) @@ -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: @@ -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, diff --git a/setup.py b/setup.py index 8f54583..c597a92 100644 --- a/setup.py +++ b/setup.py @@ -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',