-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-64.scm
43 lines (37 loc) · 1.69 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#lang sicp
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
(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))))))))
(list->tree '(1 3 5 7 9 11))
;a)
;Takes a list then gets median element of list and create a node with an entry as this median element,
;left branch is partial-tree called recursively but with half length, and because of the length
;it will also return right part (all the remaining elements) untouched as a cdr
;which will be used to create the right branch
;b)
;First from the fact that list->tree uses length it cannot be better than O(n),
;lets check partial-tree implementation
;the fact that it splits array in 2 parts recursively makes it O(logn),
;but it also goes through each and every element of list and set them as tree entry,
;hence it's O(n) too, and the whole algorithm is O(n)