# SICP Exercise 2.65

Code

```
#lang racket
; ordered set with no duplicates 2.62
(define (intersection-set set1 set2)
(if (or (null? set1) (null? set2))
'()
(let ((x1 (car set1)) (x2 (car set2)))
(cond ((= x1 x2) (cons x1 (intersection-set (cdr set1) (cdr set2))))
((< x1 x2) (intersection-set (cdr set1) set2))
((< x2 x1) (intersection-set set1 (cdr set2)))))))
(define (union-set set1 set2)
(cond
((null? set1) set2)
((null? set2) set1)
(else
(let ((x1 (car set1)) (x2 (car set2)))
(cond
((< x1 x2) (cons x1 (union-set (cdr set1) set2)))
((< x2 x1) (cons x2 (union-set set1 (cdr set2))))
(else (cons x1 (union-set (cdr set1) (cdr set2)))))))))
; set as binary tree 2.63
(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 (tree->list-2 tree)
(define (copy-to-list tree result-list)
(if (null? tree)
result-list
(copy-to-list (left-branch tree)
(cons (entry tree)
(copy-to-list (right-branch tree)
result-list)))))
(copy-to-list tree '()))
; transform ordered list to balanced binary tree 2.64
(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 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))))))))
; O(n) operations on the balanced binary tree set
(define (adjoin-tree-set x set)
(list->tree (cons x (tree->list-2 set))))
(define (intersection-tree-set set1 set2)
(list->tree (intersection-set
(tree->list-2 set1)
(tree->list-2 set2))))
(define (union-tree-set set1 set2)
(list->tree (union-set
(tree->list-2 set1)
(tree->list-2 set2))))
; tests
(define tree1 (list->tree '(1 2 3 4)))
(define tree2 (list->tree '(3 4 5 6)))
(tree->list-2 (intersection-tree-set tree1 tree2))
(tree->list-2 (union-tree-set tree1 tree2))
```

Output

```
'(3 4)
'(1 2 3 4 5 6)
```

- Convert a set based on balanced binary tree to a set based on ordered list.
- Perform operations of union/intersection.
- Convert a set based on ordered list to a set based on balanced binary tree.

In all cases time is \(O(n)\), so the total time is also \(O(n)\).