Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a binary search tree in clojure

Tags:

clojure

I am trying to become familiar with Clojure and so I've started to implement some basic algorithm and data structures. I currently have a problem with implementing a binary search tree. Here is my code:

(defstruct bst :left :right :key)

(defn add-bst [n bst-t]
  (cond
    (nil? bst-t) (struct-map bst :left nil :right nil :key n)
    (< n (:key bst-t))  (struct-map bst :left (add-bst n (:left bst-t))
                                :right (:right bst-t) :key (:key bst-t))
    (> n (:key bst-t))  (struct-map bst :left (:left bst-t)
                                :right (add-bst n (:right bst-t)) :key (:key bst-t))
    true bst-t))

I was trying to add random number into BST in the REPL, line so:

(exercise.new-ns/add-bst 5 nil)

But I get a NullPointerException, but I don't understand why I am getting this exception. Is there something wrong with my code?

like image 289
haluk Avatar asked Feb 11 '26 19:02

haluk


1 Answers

I suspect it is because you are re-using "bst" in your function parameters, which is confusing struct-map when the value is nil....

Try renaming the function parameter to something else.

like image 174
mikera Avatar answered Feb 15 '26 17:02

mikera



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!