-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.64.scm
31 lines (25 loc) · 924 Bytes
/
2.64.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(define (make-tree entry left-branch right-branch)
(list entry left-branch right-branch))
(define (list->tree elements)
(car (partial-tree elements (length elements))))
(define (partial-tree elts n)
(if (= n 0)
(cons '() elts)
(let ((left-size (quotient (- n 1) 2)))
(let ((left-result (partial-tree elts left-size)))
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
(right-size (- n (+ left-size 1))))
(let ((this-entry (car non-left-elts))
(right-result (partial-tree (cdr non-left-elts) right-size)))
(let ((right-tree (car right-result))
(remaining-elts (cdr right-result)))
(cons (make-tree this-entry left-tree right-tree) remaining-elts))))))))
; a)
(list->tree (list 1 3 5 7 9 11))
; 5
; / \
; 1 9
; \ / \
; 3 7 11
; b) O(n)