Skip to content

Instantly share code, notes, and snippets.

@zerg000000
Created February 15, 2013 03:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerg000000/4958403 to your computer and use it in GitHub Desktop.
Save zerg000000/4958403 to your computer and use it in GitHub Desktop.
A clojure implement of binary search tree
(ns com.example.bst)
; using {:val :left :right} as tree data structure
(defn node [val & [left right other]]
{:val val :left left :right right :bag other})
(defn insert [parent i-node]
(let [i-val (:val i-node)
p-val (:val parent)
side (cond (> i-val p-val) :left
(< i-val p-val) :right
:else nil)]
(if side
(assoc parent side
(if (nil? (side parent))
i-node
(insert (side parent) i-node)))
parent)
))
(defn search [node sval]
(let [val (:val node)]
(if node
(cond (= val sval) node
(> val sval) (search (:right node) sval)
(< val sval) (search (:left node) sval)
:else nil)
nil)))
(defn n-min [node]
(if (:right node)
(n-min (:right node))
(:val node)
))
(defn n-max [node]
(if (:left node)
(n-max (:left node))
(:val node)
))
; test
(def root (atom (node 0 nil nil)))
(swap! root (fn [r] (insert r (node 1 nil nil))))
(swap! root (fn [r] (insert r (node -1 nil nil))))
(swap! root (fn [r] (insert r (node 2 nil nil))))
(swap! root (fn [r] (insert r (node 7 nil nil))))
(swap! root (fn [r] (insert r (node 19 nil nil))))
(swap! root (fn [r] (insert r (node -3 nil nil))))
(swap! root (fn [r] (insert r (node 22 nil nil))))
(println @root)
(println (search @root 19))
(println (n-min @root))
(println (n-max @root))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment