Jean Guillaume Pyraksos
2009-05-21 16:49:55 UTC
Hi, a small problem. Let's represent binary trees. Leaves are themselves
and nodes are built with tree(r,ls,rs).
Ex: tree(+,tree(*,x,2),tree(-,y,1))
which represents (+ (* x 2) (- y 1)) in Lisp for example.
Problem : program copytree(t) which returns a copy of the tree t,
functionally of course, but with an iterative (tail recursive)
process, using a stack.
I solve this with a two-phase algorithm :
- first build *iteratively* the postfix walking of the tree into a list :
[+,x,2,*,y,1,-,+]
- then walk *iteratively* this list to rebuild a new tree.
Is there a more simple one-phase way (iterative and functional,
first order please, no CPS) to get this algorithm ?
*iteratively* means as usual that the stack space usage is O(1).
Thanks,
JG
and nodes are built with tree(r,ls,rs).
Ex: tree(+,tree(*,x,2),tree(-,y,1))
which represents (+ (* x 2) (- y 1)) in Lisp for example.
Problem : program copytree(t) which returns a copy of the tree t,
functionally of course, but with an iterative (tail recursive)
process, using a stack.
I solve this with a two-phase algorithm :
- first build *iteratively* the postfix walking of the tree into a list :
[+,x,2,*,y,1,-,+]
- then walk *iteratively* this list to rebuild a new tree.
Is there a more simple one-phase way (iterative and functional,
first order please, no CPS) to get this algorithm ?
*iteratively* means as usual that the stack space usage is O(1).
Thanks,
JG