August 19, 2024
P67 - A string representation of binary trees
Somebody represents binary trees as strings of the following type (see example opposite):
a(b(d,e),c(,f(g,)))
a) Write a Lisp function which generates this string representation, if the tree is given as usual (as nil or (X L R) expression). Then write a function which does this inverse; i.e. given the string representation, construct the tree in the usual form.
lisp
(defun string-rep (tree)
(cond
((null tree) "")
((and (null (second tree)) (null (third tree)))
(symbol-name (first tree)))
(t (concatenate 'string
(symbol-name (first tree))
"("
(string-rep (second tree))
","
(string-rep (third tree))
")"
)
)
)
)