简体   繁体   English

方案二叉搜索树添加元素

[英]Scheme Binary Search Tree Adding Elements

To begin, I wanted to write a function that:首先,我想编写一个函数:

Takes in:吸收:

  • A list of natural numbers, (list 2 6 1 23...) that could have repeating elements called "lst"一个自然数(list 2 6 1 23...)(list 2 6 1 23...)可能有重复元素称为“lst”

  • A random binary search tree called "bst"称为“bst”的随机二叉搜索树

Outputs:输出:

  • An updated binary tree that adds every number on the list to it一个更新的二叉树,将列表中的每个数字添加到它

Code代码

(define (recurse-lst bst lst)
  (cond [(empty? roster) empty]
        [(empty? lst) empty]
        [else (recurse-lst (bst-add bst (first lst)) (rest lst))]))

; helper function
(define (bst-add bst sublst)
  (cond [(empty? bst) (make-node (first sublst) empty empty)]
        [(< (first sublst) (node-key bst))
         (make-node (node-key bst)
                    (bst-add (node-left bst) (first sublst))
                    (node-right bst))]
        [else
         (make-node (node-key bst) (node-left bst)
                    (bst-add (node-right bst) (first sublst)))]))

Problem问题

I'm currently trying to get this working for nested lists;我目前正在尝试使其适用于嵌套列表; for example (list (list 1) (list 2)...), with each sub-list only having one element in them.例如 (list (list 1) (list 2)...),每个子列表中只有一个元素。 However, it seems that it does not work and (first sublst) in bst-add turns the sublst into a number, like (first 1).但是,它似乎不起作用,并且 bst-add 中的 (first sublst) 将 sublst 转换为数字,例如 (first 1)。

I think I've had similar bugs in other pieces of code before, but I cannot recall when and what it was.我想我以前在其他代码段中也有过类似的错误,但我不记得是什么时候发生的。

right now you have现在你有

(define (recurse-lst bst lst)
   (cond [(empty? roster)
       ....

" lst ". lst ”。

" roster ". roster ”。

you need always to include your error messages in the posts on SO.您需要始终在 SO 上的帖子中包含您的错误消息。

next.下一个。 you call (bst-add bst (first lst)) so the second argument in that call is already a number.您调用(bst-add bst (first lst))因此该调用中的第二个参数已经是一个数字。 yet in the definition of bst-add you name second parameter as " sublst " and treat it as a list.但是在bst-add的定义中,您将第二个参数命名为“ sublst ”并将其视为列表。 no need to take first again.没必要再拿first and in fact taking first of a number is an error.事实上,取first一个数字是错误的。

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

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