[plt-scheme] Excersise 14.2.3 - HtDP - Ordered list of binary tree nodes

From: Marco Morazan (morazanm at gmail.com)
Date: Fri Feb 20 16:28:08 EST 2009

> ;; inorder : BT -> list
> ;; to ouput the nodes of BT in an order of
> ;; left to right
>
> ;; Examples
>  ; (inorder false) -> empty
>
>
>  ; (inorder (make-node 1 'a false false)) -> (list 1)
>
>
>  ; (inorder (make-node 1 'a (make-node 2 'b false false) (make-node 3
> 'c false false false)))
> ;   -> (list 2 1 3)
>
>
>  ; (inorder (make-node 1 'a (make-node 2 'b (make-node 3 'c false false)
> ;                                           (make-node 4 'd false false))
> ;                           (make-node 5 'e (make-node 6 'f false false)
> ;                                           (make-node 7 'g false false))))
> ;   -> (list 3 2 4 1 6 5 7)
>
>
> ;; Template
> ; (define (inorder BT)
> ;   (cond
> ;     [(false? BT) ...]
> ;     [else (... (node-ssn BT) ...)
> ;           (... (inorder (node-left BT)) ...)
> ;           (... (inorder (node-right BT)) ...)]))
>

All this look right. Good job!

> Maybe the template is whats getting me into trouble. I struggle on
> occasion to decide where I should put the "natural recursions".
>

No, it is not the template. It seems to me that you are not thinking
about how (node-ssn BT), (inorder (node-left BT)), and (inorder
(node-right BT))  have to be combined to get the answer you need. One
of the steps of the DR that I mentioned you are not following. Hint:
It is OK to use these expressions in a different order.

Consider your example:

(inorder (make-node 1 'a (make-node 2 'b false false) (make-node 3 'c
false false false)))

Ask yourself:

(node-ssn BT) = ???
(inorder (node-left BT)) = ???
(inorder (node-right BT)) = ???

Once you have the answer for the above. Ask yourself how do you
combine them to get (list 2 1 3).

You are on the verge of the solution.

-- 

Cheers,

Marco


Posted on the users mailing list.