; rbtree.ss - Red-Black tree ; ; Copyright (c) 2010 Higepon(Taro Minowa) ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; ; 1. Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; ; 2. Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ; #| Title: Red-Black tree Example: (start code) (end code) library: (rbtree) |# (library (rbtree) (export rbtree? check-rbtree rbtree-set! rbtree-keys rbtree-delete! rbtree-get rbtree-size rbtree-contains? make-rbtree rbtree->dot ) (import (rnrs) (srfi :48)) (define-record-type rbtree (fields (mutable root) (mutable size) (immutable key=?) (immutable keydot rb . port) (define (print-node-color node port) (if (black? node) (format port " ~s [style = filled, fillcolor = \"#cccccc\"];\n" (node-key node)) (format port " ~s [style = filled, color = \"#336666\", fillcolor = \"#CC9999\"];\n" (node-key node)))) (let ([port (if (pair? port) (car port) (current-output-port))]) (format port "digraph rbtrees {\n") (node-fold '() (lambda (accum node) (let ([left (node-left node)] [right (node-right node)]) (print-node-color node port) (cond [(not left) (let ([nil (gen-nil)]) (format port " ~s [style = filled, fillcolor = \"#cccccc\"];\n" nil) (format port " ~s -> ~s;\n" (node-key node) nil))] [else (print-node-color left port) (format port " ~s -> ~s;\n" (node-key node) (node-key left))]) (cond [(not right) (let ([nil (gen-nil)]) (format port " ~s [style = filled, fillcolor = \"#cccccc\"];\n" nil) (format port " ~s -> ~s;\n" (node-key node) nil))] [else (print-node-color right port) (format port " ~s -> ~s;\n" (node-key node) (node-key right))]) )) (rbtree-root rb)) (display "}\n" port))) ;; internal procedures (define (binary-search-tree? rb) (call/cc (lambda (break) (node-fold #f (lambda (prev-key node) (cond [(and prev-key (or ((rbtree-key=? rb) prev-key (node-key node)) ((rbtree-key