Created
March 4, 2012 16:43
-
-
Save hans/1973810 to your computer and use it in GitHub Desktop.
Non-performant binary tree implementation in Clojure
This file contains hidden or 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 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