有人说这个问题是重复的。我看了另一个问题,它是一种不同于方案的编程语言。
我试图编写一个函数(小于x树),它将显示树中小于或等于x的所有节点。
我有一个旧代码,它返回树的最小值,但我不知道如何返回值列表?这只看在树的左边。在两个子树(左和右)中,它的外观如何?
(define (bst-smallest bs-tree)
(cond ((null? bs-tree)
'())
((null? (bst-left bs-tree))
(bst-value bs-tree))
(else
(bst-smallest (bst-left bs-tree)))))发布于 2015-11-16 02:05:11
一个简单的解决方案是在树上迭代(我将使用有序遍历来保持顺序),并将所有恰好小于或等于给定值的元素累加到列表中。请注意,第二个条件利用了树的顺序来避免遍历树上的元素,这些元素必须大于我们要寻找的元素:
(define (bst-lte bs-tree value)
(cond ((null? bs-tree) ; if tree is empty
'()) ; return empty list
((> (bst-value bs-tree) value) ; if current element > value
(bst-lte (bst-left bs-tree) value)) ; go to the left
(else ; else advance recursion
(append ; `append` the result
(bst-lte (bst-left bs-tree) value) ; traverse the left subtree
(list (bst-value bs-tree)) ; add it to the answer
(bst-lte (bst-right bs-tree) value))))) ; traverse the right subtree发布于 2015-11-16 02:05:12
您不想直接返回一个值列表。先建一棵树就更有意义了。
想想你的基本案子。调用输入树iTree和目标值x
这不是有效的代码,但是应该很容易适应您的实现。
https://stackoverflow.com/questions/33727072
复制相似问题