Reputation: 1178
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?
Upvotes: 3
Views: 1331
Reputation: 106401
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.
Upvotes: 3