Skip to content

Instantly share code, notes, and snippets.

@meriororen
Created December 12, 2017 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meriororen/9a5daad7aad464f4df74cd022436c798 to your computer and use it in GitHub Desktop.
Save meriororen/9a5daad7aad464f4df74cd022436c798 to your computer and use it in GitHub Desktop.
Having fun with tree in racket!
#lang racket
(require pict/tree-layout)
(require pict)
(struct node (val left right) #:transparent)
(define-struct/contract leaf ([x (not/c null?)]) #:transparent)
(define (make-tree xs)
(if (null? xs)
null
(if (null? (cdr xs))
(leaf (car xs))
(let* ([head (car xs)]
[tail (cdr xs)]
[left (filter (lambda (x) (< x head)) tail)]
[right (filter (lambda (x) (>= x head)) tail)])
(node head (make-tree left) (make-tree right))))))
(define (in-order bt)
(cond [(node? bt) (in-order (node-left bt))
(printf "~a " (node-val bt))
(in-order (node-right bt))]
[(leaf? bt) (printf "[~a] " (leaf-x bt))]))
(define (pre-order bt)
(cond [(node? bt) (printf "~a " (node-val bt))
(pre-order (node-left bt))
(pre-order (node-right bt))]
[(leaf? bt) (printf "[~a] " (leaf-x bt))]))
(define (post-order bt)
(cond [(node? bt) (post-order (node-left bt))
(post-order (node-right bt))
(printf "~a " (node-val bt))
]
[(leaf? bt) (printf "[~a] " (leaf-x bt))]))
(define (make-balanced-tree xs)
(if (null? xs)
null
(if (null? (cdr xs))
(leaf (car xs))
(let* ([mid (floor (/ (length xs) 2))]
[left (take xs mid)]
[right (drop xs mid)])
(node (car right) (make-balanced-tree left) (make-balanced-tree (cdr right)))))))
(define (bt->tree-layout bt)
(cond [(node? bt) (tree-layout #:pict (text (~a (node-val bt))) (bt->tree-layout (node-left bt)) (bt->tree-layout (node-right bt)))]
[(leaf? bt) (tree-layout #:pict (text (~a (leaf-x bt))))]
[(null? bt) #f]))
(define a (bt->tree-layout (make-balanced-tree (sort '(3 2 4 8 9 7 2 9 8 3 4 5 8 7 5 2 1 10 28 37 29 100 6 3 4 6 2 101 192 200 1) <))))
(naive-layered a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment