Search Range in Binary Search Tree I have implemented this algorithm, but I would like to get ride of the variable res, which is outside the Solution class, could anyone help me with this?

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
res = []
class Solution:
    """
    @param root: The root of the binary search tree.
    @param k1 and k2: range k1 to k2.
    @return: Return all keys that k1&lt;=key&lt;=k2 in ascending order.
    """     
    def searchRange(self, root, k1, k2):
        # write your code here
        if root is None:
            return []
        if root.val &gt; k1:
            self.searchRange(root.left, k1, k2)
        if root.val &gt;= k1 and root.val &lt;= k2:
            res.append(root.val)
        if root.val &lt; k2:
            self.searchRange(root.right, k1, k2)
        return res
You should change searchRange to search_range as per PEP8, Python's style guide.
If this is Python2 then you should use Solution(object). (This is why we have version tags).
res should go in the function. As per RobertB's comment.
Just call searchRange twice and you will clearly see why.
root, k1 and k2 are all bad names.
Rename them to better ones.
E.G. node, minimum and maximum, respectively.
You should use k1 &lt;= root.val &lt;= k2 instead of root.val &gt;= k1 and root.val &lt;= k2.
There is currently no need to return []. return None or any return work as well.
If you wrap searchRange in another function, it can be much simpler.


If I were to do most of the above. (I didn't put it in a class.)

def search_range(root, minimum, maximum):
    nodes = []

    def recursive_search(node):
        if node is None:
            return None

        if node.val &gt; minimum:
            recursive_search(node.left)
        if minimum &lt;= node.val &lt;= maximum:
            nodes.append(node.val)
        if node.val &lt; maximum:
            recursive_search(node.right)

    recursive_search(root)
    return nodes