简体   繁体   中英

Binary Search tree in Scheme

I have a scheme function where I have a list and I am trying to put the numbers into a Binary Search Tree one by one. However, I keep getting "unspecified return value"

(define (insertB L)
   (if (not (null? L))
   (begin (let() BST (insert (car L) BST))
   (insertB (cdr L))
   )
   )
)

I know my insert function works for a single number. But I need to get insertB to work for a list.

Try this:

(define (insertB BST L)
  (if (null? L)
      BST
      (insertB (insert (car L) BST)
               (cdr L))))

It's better if we pass BST along as a parameter, instead of using a global definition. Other than that, you have to make sure of returning the modified tree when we finish traversing the list (base case). Also notice how at each recursive call we insert the current element in the tree and pass it along, and at the same time we go to the next element in the list. If higher-order procedures are allowed, we can write a simpler, equivalent solution:

(define (insertB BST L)
  (foldr insert BST L))

Can you generalize the BST parameter like this?

(define (insertB L BST)
  (if (not (null? L))
    (insertB (cdr L) (insert (car L) BST))
    BST
  )
)

Or the equivalent:

(define (insertB L BST)
  (if (null? L)
    BST
    (insertB (cdr L) (insert (car L) BST))
  )
)

I think it's easier to understand. It's also more general.

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