Implementing a binary search tree in clojure

I am trying to familiarize myself with Clojure, and so I started to implement some basic algorithms and data structures. I am currently having 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 tried to add a random number in BSTin the REPL line like this:

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

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

+3
source share
1 answer

I suspect this is because you are reusing "bst" in your function parameters, which confuses the struct-map structure when the value is nil ....

Try renaming the function parameter to another.

+3
source

Source: https://habr.com/ru/post/1790503/


All Articles