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)))
))
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)))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With