Insert node key and value in binary search tree us

2019-08-09 14:24发布

I am inserting a key key and a value val into the tree-map t returning a new tree with a node containing the key and the value in the appropriate location.

I have this defined:

(define (tree-node key value left right)(list key value left right))

(define (get-key tn) (node_key tn))
(define (get-val tn) (node_val tn))
(define (get-left tn) (node_left tn))
(define (get-right tn) (node_right tn))

(define (node_key tn) (list-ref tn 0))
(define (node_val tn) (list-ref tn 1))
(define (node_left tn) (list-ref tn 2))
(define (node_right tn) (list-ref tn 3))

Im trying this insert method

(define (insert t key val)

  (cond (empty? t))
  (tree-node (key val '() '()))

  ((equal key (get-key t))
   (tree-node (key val (get-left t) (get-right t)))

   ((<key (get-key t))
    (tree-node ((get-key t) (get-val t) (insert (get-left t key val)) (get-right t)))
    (tree-node ((get-key t) (get-val t) (get-left t) (insert (get-right t key val)))))))

I'm using this to define

(define right (insert (insert empty 3 10) 5 20))

and I'm getting this error in DrRacket

application: not a procedure;
expected a procedure that can be applied to arguments
given: (list 0 1 2)
arguments...: [none]

1条回答
虎瘦雄心在
2楼-- · 2019-08-09 15:13

What is happening is that a tree-node (which is just a list) is being returned in a position where a function is expected. Scheme cannot execute the list - it's not a function, so it's complaining.

I suspect this is because you have messed up your parentheses.

(cond (empty? t))

Is a self-contained compound expression. It is evaluated, returning the value of t. The expressions after that are not evaluated as part of the cond.

查看更多
登录 后发表回答