I\'m trying to modify a representation of a tree from : (A 2 B 0 C 2 D 0 E 0) in (A (B) (C (D) (E))). My code is like:
(defun transform(l)
(cond
( (null l)
An answer to this is given by https://stackoverflow.com/a/34193414/1250772 as part of a response to a user who is evidently working through the same homework problem. The solution is based on reversing the prefix notation into postfix, and then interpreting it as a stack-based reverse polish notation for constructing a tree.
By coincidence, the following code from that answer produces the same representation as what you're asking for. I came up with that representation impromptu, in order to solve the inorder traversal problem in that question:
(defun build-tree (syntax)
(let ((rs (reverse syntax))
(stack))
(dolist (item rs (pop stack)) ;; heart of the interpreter loop
(cond ((integerp item) (push item stack)) ;; integer instruction
((symbolp item) (let ((num (pop stack))) ;; sym instruction
;; construct node using backquote, and
;; put it on the stack.
(push `(,item ,@(loop repeat num
collect (pop stack)))
stack)))))))