我的代码目前允许我搜索特定节点,我想编辑它以便我可以在一系列数字中搜索。例如,我有一个苹果的价格表,我想将所有苹果添加到价格在2美元到4美元之间的列表/字典中。
这是我目前的代码
#<JUG-STATE {1004BD8F53}>
--------------------
Class: #<STANDARD-CLASS COMMON-LISP-USER::JUG-STATE>
--------------------
Group slots by inheritance [ ]
Sort slots alphabetically [X]
All Slots:
[ ] FIVE = 0
[ ] TWO = 2
[set value] [make unbound]
我认为我应该编辑目标,将其从单项搜索更改为远程项搜索,但我不是100%确定如何
答案 0 :(得分:1)
使用递归的有序遍历:
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 > a:
self._traverse_range(subtree.left, a, b, cumresult)
# Push VALUE if it is in our range.
if a <= subtree.key <= b: # Change to strict "< 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 < b:
self._traverse_range(subtree.right, a, b, cumresult)
return cumresult