Created
February 15, 2013 03:35
-
-
Save zerg000000/4958403 to your computer and use it in GitHub Desktop.
A clojure implement of binary search tree
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
(ns com.example.bst) | |
; using {:val :left :right} as tree data structure | |
(defn node [val & [left right other]] | |
{:val val :left left :right right :bag other}) | |
(defn insert [parent i-node] | |
(let [i-val (:val i-node) | |
p-val (:val parent) | |
side (cond (> i-val p-val) :left | |
(< i-val p-val) :right | |
:else nil)] | |
(if side | |
(assoc parent side | |
(if (nil? (side parent)) | |
i-node | |
(insert (side parent) i-node))) | |
parent) | |
)) | |
(defn search [node sval] | |
(let [val (:val node)] | |
(if node | |
(cond (= val sval) node | |
(> val sval) (search (:right node) sval) | |
(< val sval) (search (:left node) sval) | |
:else nil) | |
nil))) | |
(defn n-min [node] | |
(if (:right node) | |
(n-min (:right node)) | |
(:val node) | |
)) | |
(defn n-max [node] | |
(if (:left node) | |
(n-max (:left node)) | |
(:val node) | |
)) | |
; test | |
(def root (atom (node 0 nil nil))) | |
(swap! root (fn [r] (insert r (node 1 nil nil)))) | |
(swap! root (fn [r] (insert r (node -1 nil nil)))) | |
(swap! root (fn [r] (insert r (node 2 nil nil)))) | |
(swap! root (fn [r] (insert r (node 7 nil nil)))) | |
(swap! root (fn [r] (insert r (node 19 nil nil)))) | |
(swap! root (fn [r] (insert r (node -3 nil nil)))) | |
(swap! root (fn [r] (insert r (node 22 nil nil)))) | |
(println @root) | |
(println (search @root 19)) | |
(println (n-min @root)) | |
(println (n-max @root)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment