# jiacai2050/sicp

Switch branches/tags
Nothing to show
Fetching contributors…
Cannot retrieve contributors at this time
75 lines (60 sloc) 2.21 KB

``````(load "lib/tree.scm")
(define (mid-index x)
(if (even? x)
(/ x 2)
(/ (+ 1 x) 2)))

(define (nth-element elements index)
(define (iter elts current)
(if (= 1 current)
(car elts)
(iter (cdr elts) (- current 1))))
(iter elements index))

(define (lower-elements elements index)
(define (iter elts current result)
(if (= 1 current)
result
(iter (cdr elts) (- current 1) (append result (list (car elts))))))
(iter elements index '()))

(define (higher-elements elements index)
(define (iter elts current)
(if (= 1 current)
(cdr elts)
(iter (cdr elts) (- current 1))))
(iter elements index))

(define (list->tree elements length)
(if (< length 1)
'()
(let ((mid (mid-index length)))
(let ((mid-element (nth-element elements mid))
(left (lower-elements elements mid))
(right (higher-elements elements mid)))
(make-tree mid-element
(list->tree left (- mid 1))
(list->tree right (- length mid)))))))

(define (make-tree-set elements)
(list->tree elements (length elements)))

(make-tree-set '(1 2 3 4 5 6 7))
;Value: (4 (2 (1 () ()) (3 () ())) (6 (5 () ()) (7 () ())))
;格式化后更直观些
; (4 (2 (1 () ())
;       (3 () ()))
;    (6 (5 () ())
;       (7 () ())))
``````

### a)

`partial-tree`的工作原理其实就是，先找出中间的元素来做根节点，然后依次递归调用求出左子树与右子树 最后调用`make-tree`把这三者组合起来

### b)

T(n) = 2T(n/2) + Θ(1)

T(n) = Θ(n)