Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BST-Smallest Scheme

So I'm trying to write a code that returns the smallest value in a binary search tree. I know this is the left most value of the tree and understand that I need it to recursively run to the left until there is nothing left. But my code isn't working and I don't know why. Any help would be appreciated.

(define (bst-smallest bs-tree)
  (cond ((null? bs-tree)
     (display "undefined"))
    ((< (bst-value bs-tree) (bst-value (bst-left bs-tree))) 
     (bst-value (bst-left bs-tree)))
    (else 
     (bst-smallest (bst-left bs-tree)))
    ))
like image 660
Anon Avatar asked Nov 19 '25 18:11

Anon


1 Answers

You just have to go all the way to the left on the tree, until you can't go any further. In your code, the second condition is incorrect - there's no need to test the values, we know that the leftmost element will be the minimum by construction. Try this instead:

(define (bst-smallest bs-tree)
  (cond ((null? bs-tree)
         (display "undefined"))
        ((null? (bst-left bs-tree))
         (bst-value bs-tree))
        (else
         (bst-smallest (bst-left bs-tree)))))
like image 167
Óscar López Avatar answered Nov 23 '25 22:11

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!