I'm studying algorithms and at the class we were asked to create a BST with structures, I'm trying really hard to create a delete function but the one I created isn't efficient and doesn't work. I searched in google for something similar, but most of the questions are about vectors and not record/structures. If you have any recommendations, I would really appreciate it.
This is the basic creating of the root and node:
(let [bst (make-bst)]
(bst-empty? bst)
(make-bst-node 10))
(defrecord BST [root])
(defn bst? [bst]
(= (class bst) BST))
(defn make-bst []
(BST. (ref nil)))
(defn bst-empty? [bst]
(nil? @(:root bst)))
(defrecord BSTnode [data left right])
(defn make-bst-node [val]
(BSTnode. val (ref nil) (ref nil)))
(defn bst-insert! [bst val]
(loop [node (:root bst)]
(if (nil? @node)
(dosync
(ref-set node (make-bst-node val)))
(let [data (:data bst)]
(if (< val data)
(recur (:left @node))
(if (val data)
(recur (:right @node))))))))
This is the delete function:
(defn bst-del [bst val]
(if (nil? @(:root bst))
false
(do
(if (= (:data @(:root bst)) val)
(if (nil? (and (:right bst) (:left bst)))
(dosync
(ref-set (:root bst) nil))
(if (not (nil? (:right bst)))
(dosync
(ref-set (:root bst) @(:right bst)))
(if (not (nil? (:left bst)))
(dosync
(ref-set (:root bst) @(:left bst)))
(if (not (nil? (and (:right bst) (:left bst))))
(dosync
(ref-set (:root bst) @(:left bst))
(ref-set (:root bst) (:right bst))) false))))))))
(defn node-del [bst val]
(loop [node @(:root bst)]
(if (nil? node)
false
(if (true? bst-del)
(println "somthing got deleted")
(if (< val (:data node))
(recur @(:left node))
(recur @(:right node)))))))
I tried to search in google but all the function or examples were for maps and vectors, not my case, as well as, reading theoretical material about the subject and references from different languages.
this code of yours seems to be overly complicated and hard to debug (or event understand an algorithm)
I would propose implementing this recursive algorithm for deletion, which works quite nice with that mutable structure of yours:
so, i would start with the following type defs:
first thing we want is insertion + traversal functions for tree creating/debug. let's implement them for
Node(and employ inTreelater):so, this seems to work ok.
Next, we will implement the deletion algorithm. there's an utility function
minimumin the aforementioned algorithm, so we start with that one:after that the deletion implementation looks trivial:
this seems to be working mutable algorithm.
Let's then go back to the
Treestructure. I would start with theBSTprotocol, to be used by bothNodeandTree:and that's it. Now just use it: