How to implement 'range' with a python BST
<p>My code at the moment allows me to search for a specific node, I would like to edit it so that I can search within a range of numbers. For example, I have a price list of apples, and I would like to add all apples to a list/dictionary that cost between $2-$4 or something like that. </p>

<p>Here is my current code</p>

<pre><code>def valueOf(self, key):
    node = self._bstSearch(self._root, key)
    assert node is not None, "Invalid map key."
    return node.value

def _bstSearch(self, subtree, target):
    if subtree is None:
        return None
    elif target &lt; subtree.key:
        return self._bstSearch( subtree.left, target)
    elif target &gt; subtree.key:
        return self._bstSearch(subtree.right, target)
    else:    
        return subtree
</code></pre>

<p>I think I should be editing target to change it from a single item search to a ranged item search but I'm not 100% sure how to</p>

<p><strong>Using recursive in-order traversal:</strong></p>

<pre><code>def range(self, a, b):
    return self._traverse_range(self._root, a, b)

def _traverse_range(self, subtree, a, b, cumresult=None):
    if subtree is None:
        return

    # Cumulative variable.
    if cumresult is None:
        cumresult = []

    # Traverse LEFT subtree if it is possible to find values in required range there.
    if subtree.key &gt; a:
        self._traverse_range(subtree.left, a, b, cumresult)

    # Push VALUE if it is in our range.
    if a &lt;= subtree.key &lt;= b:  # Change to strict "&lt; b" to act like python's range
        cumresult.append(subtree.key)

    # Traverse RIGHT subtree if it is possible to find values in required range there.
    if subtree.key &lt; b:
        self._traverse_range(subtree.right, a, b, cumresult)

    return cumresult
</code></pre>

python binary-search-tree