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)

 


(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))

view raw

s228.scm

hosted with ❤ by GitHub

 

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading