In: Computer Science
Consider an implementation of binary trees with Scheme lists, as in the following example:
Before proceeding, it may be useful to define three auxiliary functions (left T), (right T) and (val T) which return the left subtree, the right subtree, and the value in the root of tree T, respectively.
(a) Write a recursive function (n-nodes T), which returns the number of nodes in the tree T. The following example illustrates the use of this function:
> (n-nodes T)
8
(b) Write a recursive function (n-leaves T), which returns the number of leaves
in the tree T. The following example illustrates the use of this function:
> (n-leaves T)
4
(c) (15 pts) The height of a tree is defined as the maximum number of nodes on a path from the root to a leaf. Write a recursive function (height T), which returns the height of the tree T. The following example illustrates the use of this function:
> (height T)
4
(d) (15 pts) Write a recursive function (postorder T), which returns the list of all elements in the tree T corresponding to a postorder traversal of the tree. The following example illustrates the use of this function:
>
(postorder T)
(1 9 8 5 17 25 22 13)
(define T
'(13
(5
(1 () ())
(8 ()
(9 () ())
)
)
(22
(17 () ())
(25 () ())
)
)
)
(define (val T) (car T))
(define (left T) (cadr T))
(define (right T) (caddr T))
(define (n-nodes T)
(cond ((null? T) 0)
(else (+ 1 (n-nodes (left T))
(n-nodes (right T))))))
(define (n-leaves T)
(cond ((null? T) 0)
((and (null? (left T)) (null?
(right T))) 1)
(else (+ (n-leaves (left T))
(n-leaves (right T))))))
(define (height T)
(cond ((null? T) 0)
(else (+ 1 (max (height (left T)) (height (right T)))))))
(define (postorder T)
(cond ((null? T) '())
(else (append (postorder (left T)) (postorder (right T))
(list (val T))))))