Python 从二叉树收集特定范围内的值?
例如{Range:4,6}将在此处返回[4,5,5,6]:Python 从二叉树收集特定范围内的值?,python,recursion,binary-tree,binary-search-tree,Python,Recursion,Binary Tree,Binary Search Tree,例如{Range:4,6}将在此处返回[4,5,5,6]: def allInRange(bst, left, right): if bst is EmptyValue: return if left <= bst.root <= right: print(bst.root) allInRange(bst.left, left, right) allInRange(bst.right, left, right) def
def allInRange(bst, left, right):
if bst is EmptyValue:
return
if left <= bst.root <= right:
print(bst.root)
allInRange(bst.left, left, right)
allInRange(bst.right, left, right)
def allInRange(bst,左,右):
如果bst为空值:
返回
如果左,则取决于二叉树的实现方式。请首先向我们展示树的定义,这是一个二叉搜索树(BST),而不是任何旧的二叉树。其次,在不了解BST实现的情况下,我不能给您提供比伪代码更好的代码。您的BST实现为嵌套列表、嵌套dict、自定义类还是。。。?所以我再问一次,请把你的BST的定义编辑成你的原始版本post@Oliver. 你有表示树的代码吗?表达得很清楚,@gnibbler.Where是EmptyValue
定义的?@Oliver:是的,你必须更改打印(bst.root)
行,包括退货和accumulator@Oliver:将最后两行更改为返回应该是前面提到的操作的一部分accumulator@Oliver当前位置你为什么不试试,看看结果如何。如果你想不出来,发个帖子——我们会在这里帮助你的