How do you make a binary search tree in Clojure?

好久不见. 提交于 2019-12-20 19:35:16

问题


In Scheme, I can use define-struct to make a binary search tree, but how do you do it in Clojure?


回答1:


You can use structmaps. To define one:

(defstruct bintree :left :right :key)

To make an instance:

(struct-map bintree :left nil :right nil :key 0)

You can then access the values in the struct like this:

(:left tree)

etc.

Or you can create new accessor functions:

(def left-branch (accessor bintree :left))

and use it:

(left-branch tree)



回答2:


I don't know Clojure, but I bet it's the same way you do it in Scheme without define-struct ... just cons together the left and right branches. To find something, recurse until you hit an atom.

Seriously, though, structmaps sound like what you want. I found this page. Look for structmaps about half way down.




回答3:


The simplest way would be to use the tree that is already defined in language (every sorted-map is a tree really, if you just need different function to compare keys, use sorted-map-by).

;;define function for comparing keys
(defn compare-key-fn [key1 key2] (< key1 key2) )

;;define tree and add elements
(def my-tree
  (->                              ;;syntax sugar
    (sorted-map-by compare-key-fn) ;;this returns empty tree with given function to compare keys
    (assoc 100  "data for key = 100") ;;below we add elements to tree
    (assoc 2  "data for key = 2")
    (assoc 10 "data for key = 10")
    (assoc -2 "data for key = -1")))

;;accesing  elements by key
(prn "element for key 100 =" (my-tree 100))

;;"erasing" elements from tree - in reality, what we are really doing, is returning a new tree that contains all elements of the old one, except the element we've just erased.
(def my-new-tree
  (dissoc my-tree 2))

(prn my-new-tree) ;; to verify, that element 2 is "erased"


来源:https://stackoverflow.com/questions/1611157/how-do-you-make-a-binary-search-tree-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!