-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-63.rkt
82 lines (71 loc) · 1.97 KB
/
2-63.rkt
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#lang racket
(require threading)
(require racket/trace)
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left-branch right-branch)
(list entry left-branch right-branch))
(define (element-of-set? x s)
(cond [(null? s) #f]
[(= x (entry s) #t)]
[(< x (entry s))
(element-of-set? x (left-branch s))]
[(> x (entry s))
(element-of-set? x (right-branch s))]))
(define (adjoin-set x s)
(cond [(null? s) (make-tree x '() '())]
[(= x (entry s)) s]
[(< x (entry s))
(make-tree (entry s)
(adjoin-set x (left-branch s))
(right-branch s))]
[(> x (entry s))
(make-tree (entry s)
(left-branch s)
(adjoin-set x (right-branch s)))]))
(define t (adjoin-set 1 (make-tree 2 '() '())))
(define (tree->list-1 tree)
(if (null? tree)
'()
(append (tree->list-1 (left-branch tree))
(cons (entry tree)
(tree->list-1
(right-branch tree))))))
(define (tree->list-2 tree)
(define (copy-to-list tree accu)
(if (null? tree)
accu
(copy-to-list (left-branch tree)
(cons (entry tree)
(copy-to-list
(right-branch tree)
accu)))))
(copy-to-list tree '()))
(trace tree->list-1)
(trace tree->list-2)
(define t1
(~>> null
(adjoin-set 1)
(adjoin-set 2)
(adjoin-set 3)
(adjoin-set 4)
(adjoin-set 5)
(adjoin-set 6)
(adjoin-set 7)))
(tree->list-1 t)
(tree->list-1 t)
(tree->list-2 t1)
(tree->list-2 t1)
(define t2
(~>> null
(adjoin-set 7)
(adjoin-set 6)
(adjoin-set 5)
(adjoin-set 4)
(adjoin-set 3)
(adjoin-set 2)
(adjoin-set 1)
))
(tree->list-1 t1)
(tree->list-2 t2)