简体   繁体   English

Scheme中的二叉搜索树

[英]Binary Search tree in Scheme

I have a scheme function where I have a list and I am trying to put the numbers into a Binary Search Tree one by one. 我有一个计划函数,其中有一个列表,我试图将数字逐一放入二进制搜索树中。 However, I keep getting "unspecified return value" 但是,我不断收到“未指定的返回值”

(define (insertB L)
   (if (not (null? L))
   (begin (let() BST (insert (car L) BST))
   (insertB (cdr L))
   )
   )
)

I know my insert function works for a single number. 我知道我的插入功能适用于单个数字。 But I need to get insertB to work for a list. 但是我需要获取insertB才能工作以获取列表。

Try this: 尝试这个:

(define (insertB BST L)
  (if (null? L)
      BST
      (insertB (insert (car L) BST)
               (cdr L))))

It's better if we pass BST along as a parameter, instead of using a global definition. 最好将BST作为参数传递,而不要使用全局定义。 Other than that, you have to make sure of returning the modified tree when we finish traversing the list (base case). 除此之外,您必须确保在完成遍历列表时返回修改后的树(基本情况)。 Also notice how at each recursive call we insert the current element in the tree and pass it along, and at the same time we go to the next element in the list. 还要注意,在每次递归调用时,我们如何insert当前元素insert树中并将其传递,同时我们转到列表中的下一个元素。 If higher-order procedures are allowed, we can write a simpler, equivalent solution: 如果允许使用更高阶的过程,我们可以编写一个更简单的等效解决方案:

(define (insertB BST L)
  (foldr insert BST L))

Can you generalize the BST parameter like this? 您可以像这样概括BST参数吗?

(define (insertB L BST)
  (if (not (null? L))
    (insertB (cdr L) (insert (car L) BST))
    BST
  )
)

Or the equivalent: 或等效的:

(define (insertB L BST)
  (if (null? L)
    BST
    (insertB (cdr L) (insert (car L) BST))
  )
)

I think it's easier to understand. 我认为这更容易理解。 It's also more general. 也更一般。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM