How do you make a binary search tree in Clojure?

前端 未结 3 2093
傲寒
傲寒 2021-02-08 10:04

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

3条回答
  •  猫巷女王i
    2021-02-08 10:24

    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"
    

提交回复
热议问题