Skip to content

Instantly share code, notes, and snippets.

@svard
Last active August 29, 2015 13:58
Show Gist options
  • Select an option

  • Save svard/10313226 to your computer and use it in GitHub Desktop.

Select an option

Save svard/10313226 to your computer and use it in GitHub Desktop.
Binary search tree in clojure
(ns tree.core
(:require [clojure.core.match :refer [match]]))
(defn get-max
[tree]
(match tree
nil nil
[nil x nil] x
[a x b] (recur b)))
(defn get-min
[tree]
(match tree
nil nil
[nil x nil] x
[a x b] (recur a)))
(defn insert-val
[tree x]
(let [ins (fn ins [tree]
(match tree
nil [nil x nil]
[a y b] (cond
(< x y) [(ins a) y b]
(> x y) [a y (ins b)]
:else tree)))]
(ins tree)))
(defn delete-val
[tree x]
(let [del (fn del [tree]
(match tree
nil nil
[nil x nil] nil
[[nil x nil] y a] [nil y a]
[a y [nil x nil]] [a y nil]
[[a y b] x nil] [a y b]
[nil x [a y b]] [a y b]
[a x b] (let [min (get-min b)]
[a min (delete-val b min)])
[a y b] (cond
(< x y) [(del a) y b]
(> x y) [a y (del b)]
:else tree)))]
(del tree)))
(defn search-val
[tree x]
(match tree
nil nil
[a y b] (cond
(< x y) (recur a x)
(> x y) (recur b x)
:else x)))
(defn in-order
[tree]
(when-let [[a x b] tree]
(lazy-cat (in-order a) [x] (in-order b))))
(deftype BinaryTree [tree]
clojure.lang.IPersistentSet
(cons [this v] (BinaryTree. (insert-val tree v)))
(disjoin [this v] (BinaryTree. (delete-val tree v)))
(empty [this] (BinaryTree. nil))
(equiv [this o] (if (instance? BinaryTree o)
(= tree (.tree o))
false))
(seq [this] (when tree (in-order tree)))
(get [this n] (search-val tree n))
(contains [this n] (boolean (get this n)))
clojure.lang.IFn
(invoke [this n] (get this n)))
(defn binary-tree
[xs]
(into (->BinaryTree nil) xs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment