Exercise 2.28. Write a procedure fringe that takes as argument a tree (represented as a list) and returns a list whose elements are all the leaves of the tree arranged in left-to-right order. For example,
(define x (list (list 1 2) (list 3 4)))
(fringe x)
(1 2 3 4)
(fringe (list x x))
(1 2 3 4 1 2 3 4)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (define nil '()) | |
| (define (append list1 list2) | |
| (if (null? list1) | |
| list2 | |
| (cons (car list1) (append (cdr list1) list2)))) | |
| ;; Takes as input a tree | |
| ;; Create a list of elements of the tree. | |
| ;; Inorder traversal | |
| ;; create an internal list into which elements will be added. | |
| (define (fringe x) | |
| (cond | |
| ((null? x) | |
| nil) | |
| ((not (pair? x)) | |
| (cons x nil)) | |
| (else | |
| (append | |
| (fringe (car x)) | |
| (fringe (cdr x)))))) | |
| (define x (list (list 1 2) (list 3 4))) | |
| (fringe x) | |
| (fringe (list x x)) | |