Skip to content

Instantly share code, notes, and snippets.

@keyvanakbary
Created September 3, 2014 14:43
Show Gist options
  • Save keyvanakbary/2c9f519c527100fac560 to your computer and use it in GitHub Desktop.
Save keyvanakbary/2c9f519c527100fac560 to your computer and use it in GitHub Desktop.
Immutable and persistent Binary Tree
(defrecord Node [value left right])
(defn create [value]
(Node. value nil nil))
(defn insert [{:keys [left right value] :as tree} v]
(if tree
(cond
(< v value) (Node. value (insert left v) right)
(> v value) (Node. value left (insert right v))
:else (Node. v left right))
(create v)))
(defn remove [{:keys [left right value] :as tree} v]
(cond
(< v value) (Node. value (remove left v) right)
(> v value) (Node. value left (remove right v))
:else nil))
(defn contains [{:keys [left right value] :as tree} v]
(if tree
(cond
(< v value) (contains left v)
(> v value) (contains right v)
:else true)
false))
(def btree
(-> (create 1)
(insert 2)
(insert 3)
(insert -2)
(remove -2)))
(contains btree -2)
;=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment