Skip to content

Instantly share code, notes, and snippets.

@Michaelgathara
Created March 15, 2023 21:34
Show Gist options
  • Save Michaelgathara/a8c82da602ee82c81bad53b495a57132 to your computer and use it in GitHub Desktop.
Save Michaelgathara/a8c82da602ee82c81bad53b495a57132 to your computer and use it in GitHub Desktop.
Binary Tree Racket
#lang racket
(define (create-bt line)
(match line
[`(,x0 ,x1) (if (< x0 x1) `(bt ,x0 empty (bt ,x1 covered empty)) 'empty)]
[_ 'error]
)
)
(define (insert-bt bt line)
(match line
[`(,x0 ,x1)
(match bt
['covered 'covered]
['empty (create-bt line)]
[`(bt ,root ,left ,right)
`(bt ,root ,(insert-bt left `(,(min root x0) ,(min root x1))) ,(insert-bt right `(,(max root x0) ,(max root x1))))
]
[_ bt]
)
]
)
)
(define (traverse-bt bt [x0 'init] [x1 'init])
(match bt
['empty 0]
['covered (- x1 x0)]
[`(bt ,root ,left ,right) (+ (traverse-bt left x0 root) (traverse-bt right root x1))]
[_ 0]
)
)
(create-bt `(6 9))
(define bts (insert-bt (create-bt `(6 9)) `(1 10)))
(traverse-bt (insert-bt bts `(3 4)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment