简体   繁体   English

在球拍中实施BST

[英]implementing bst in racket

I am trying to implement a bst(binary search tree) in racket. 我正在尝试在球拍中实现bst(二进制搜索树)。 The bst is a recursive list (list x leftChild rightChild) where leftChild and rightChild are lists themselves I wrote the following code bst是一个递归列表(列表x leftChild rightChild),其中leftChild和rightChild本身就是列表,我编写了以下代码

(define (insert bst x)(
     (cond 
       [(null? bst) (append bst (list x '() '()))]
       [(<= x (car bst)) (insert (cadr bst) x)]
       [else (insert (caddr bst) x)]  
     )))

when I write 当我写

(insert (insert null 8) 9)

it gives an error: function call: expected a function after the open parenthesis, but received (list 8 empty empty) Can anyone explain this? 它给出了一个错误: 函数调用:在圆括号后应该有一个函数,但是收到了(列表8空空),有人可以解释吗?

The error reported happens because there's an erroneous pair of () surrounding the cond expression, that makes Scheme try to execute a procedure when there's none. 报告错误的发生是因为cond表达式周围有一对错误的() ,这使得Scheme尝试在不存在的情况下尝试执行过程。 But there are several logic problems beyond that, you're not actually building a list when an element is inserted, and there's a case missing - what happens if the element already exists in the tree?. 但是除此之外,还有几个逻辑问题,当您插入一个元素时,您实际上并没有在构建列表,并且缺少一种情况-如果树中已经存在该元素会发生什么? This should work: 这应该工作:

(define (insert bst x)
  (cond 
    [(null? bst)
     (list x '() '())] ; this is the correct way to handle the base case
    [(= x (car bst))   ; this case was missing
     bst]              ; simply leave the tree as it is
    [(< x (car bst))   ; if this happens, recursively build a list
     (list (car bst) (insert (cadr bst) x) (caddr bst))] 
    [else              ; if this happens, recursively build a list
     (list (car bst) (cadr bst) (insert (caddr bst) x))]))

This is how you'd use the procedure: 这是使用该过程的方式:

(insert (insert (insert (insert null
                                10)
                        5)
                16)
        13)

=> '(10 (5 () ()) (16 (13 () ()) ()))

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

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