Racket:在二叉树中搜索和替换

时间:2015-03-10 07:08:23

标签: search tree scheme binary-tree racket

代码的目标是搜索密钥(k),如果找到,则用v替换该值。

(define-struct node (key value left right))

(define (insert k v tree)
  (cond
    [(empty? tree) (list k v) ]
    [(equal? (node-key tree) k) 
     (make-node  k v (insert k v (node-left tree))
                 (insert k v (node-right tree)))]
    [else (make-node (node-key tree) (node-value tree) 
                     (insert k v (node-left tree)) (insert k v (node-right tree)))])) 

(define sample (make-node 2 "two"
                          (make-node 1 "one" empty empty)
                          (make-node 3 "three" empty empty)))

示例和1“hello”的输出应为

(make-node 2 "two"
           (make-node 1 "hello" empty empty)
           (make-node 3 "three" empty empty))

而是

(make-node 2 "two"
           (make-node 1 "hello"
                      (list 1 "hello")
                      (list 1 "hello"))
           (make-node 3 "three"
                      (list 1 "hello")
                      (list 1 "hello")))

有什么建议让输出成为想要的输出吗?

1 个答案:

答案 0 :(得分:3)

下面

[(empty? tree) (list k v)]

您正在使用非空列表替换每个不存在的子树,如此小测试所示:

> (insert 1 "how" empty)
'(1 "how")

应该是

[(empty? tree) empty]