Created
September 3, 2014 14:43
-
-
Save keyvanakbary/2c9f519c527100fac560 to your computer and use it in GitHub Desktop.
Immutable and persistent Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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