Question & Answer: Consider an implementation of binary trees with Scheme lists, as in the following example: (define T ' (13 (5 (1 () ()) (8 () (9 () ()))) (22 (17 ()…..

These have to be implemented using the Scheme programming language.
I already have the building blocks made :

(define (val T)
(car T)
)

(define (left T)
(car (cdr T))
)

(define (right T)
(car (cdr (cdr T)))
)

Consider an implementation of binary trees with Scheme lists, as in the following example: (define T ‘ (13 (5 (1 () ()) (8 () (9 () ()))) (22 (17 () ())(25 () ())))) Before proceeding, it may be useful to define three auxiliary functions (val T), (left T) and (right T), which return the value in the root of tree T, its left subtree and its right subtree, respectively. (a) Write a recursive function (tree-member? V T), which determines whether V appears as an element in the tree T. The following example illustrates the use of this function: > (tree-member? 17 T) #t (b) Write a recursive function (preorder T), which returns the list of all elements in the tree T corresponding to a preorder traversal of the tree. The following example illustrates the use of this function: > (preorder T) (13 5 1 8 9 22 17 25) (c) Write a recursive function (inorder T), which returns the list of all elements in the tree T corresponding to an inorder traversal of the tree. The following example illustrates the use of this function: > (inorder T) (1 5 8 9 13 17 22 25)

Expert Answer

 

; Problem 1

(define T

‘(13

(5

(1 () ())

(8 ()

(9 () ())))

(22

(17 () ())

(25 () ()))))

; Define three auxiliary functions (left T),(right T) and (val T) which return the left sub tree, ; the right sub tree, and the value in the root of tree T, respectively.

(define (left L)

(List-ref L 1)

)

(Define (right L)

(List-ref L 2)

)

(Define (Val L)

(List-ref L 0)

)

(Define (n-nodes L)

(cond [(equal? (length L) 0) 0] [else (+ 1 (+ (n-nodes (left L)) (n-nodes (right L))))]

)

)

(Define (n-leaves L)

(cond [(equal? (length L) 0) 0]

[Else

(cond

[(equal? (+ (length (left L)) (length (right L))) 0) 1]

[else (+ (n-leaves (left L)) (n-leaves (right L)))]

)

]

)

)

(define (height L)

(cond [(equal? (length L) 0) 0]

[else (+ 1 (max (height (left L)) (height (right L))))]

)

)

(define (postorder L)

(cond [(equal? (length L) 0) ()]

[else (append (postorder (left L)) (postorder (right L))

(list (val L)))

]

)

)

; Problem 2 (define (member-bst? x L)

(cond [(equal? (length L) 0) #f]

[else

(cond [(equal? x (val L)) #t] [else (cond [(> x (val L)) (member-bst? x (right L))]

[else (member-bst? x (left L))]

)

]

)

]

)

)

Still stressed from student homework?
Get quality assistance from academic writers!