简体   繁体   中英

Racket: search and replace in a binary tree

The goal of the code was to search for a key (k) and if found, replace the value with 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)))

The output with the sample and 1 "hello" should be

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

but is instead

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

Any suggestions to cause the output to go the wanted one?

Here

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

you're replacing every non-existing subtree with a non-empty list, as shown by this little test:

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

It should be

[(empty? tree) empty]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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