Skip to content

Instantly share code, notes, and snippets.

@hans
Created March 4, 2012 16:43
Show Gist options
  • Save hans/1973810 to your computer and use it in GitHub Desktop.
Save hans/1973810 to your computer and use it in GitHub Desktop.
Non-performant binary tree implementation in Clojure
(defrecord BinaryTree [key left right]))
(defn insert [tree val]
(if (nil? tree)
(BinaryTree. val nil nil)
(let [key (:key tree)]
(cond
(< key val) (BinaryTree. key
(:left tree)
(insert (:right tree) val))
(> key val) (BinaryTree. key
(insert (:left tree) val)
(:right tree))))))
(defn remove [tree val]
(let [key (:key tree)]
(cond
(= val key) nil
(< key val) (BinaryTree. key
(:left tree)
(remove (:right tree) val))
(> key val) (BinaryTree. key
(remove (:left tree) val)
(:right tree)))))
(defn contains? [tree val]
(loop [cur-tree tree]
(if (nil? cur-tree)
false
(let [key (:key cur-tree)]
(cond
(= key val) true
(< key val) (recur (:right tree))
(> key val) (recur (:left tree)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment