-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.64.scm
26 lines (24 loc) · 1.11 KB
/
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
(define (list->tree elements)
(car (partial-tree elements (length elements))))
;; Takes an integer n arguments and list of at least n elements
;; and constructs a balanced tree containing the first n elements of
;; the list. The result returned by partial-tree is a pair (formed with
;; cons) whose car is the constructed tree and whose cdr is the list of
;; elements not included in the tree.
(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))))))))