Learning lisp for the fun of it, haven't had too much of a difficult time until now, and I'm on the third lecture of this site. I'm trying to complete the exercise "Implement a function that will create a list containing members of a given binary tree in postorder." Here's my code so far:
(defun bin-tree-postorder (b)
"Create a list containing keys of b in postorder"
(if (bin-tree-leaf-p b)
(list (bin-tree-leaf-element b))
(let
((elmt (bin-tree-node-element b))
(left (bin-tree-node-left b))
(right (bin-tree-node-right b)))
(cons
(append (bin-tree-postorder left)
(bin-tree-postorder right)) elmt))))
However, it won't run, because I get an error of:
*** - APPEND: A proper list must not end with +
Here's my trace:
1. Trace: (BIN-TREE-POSTORDER '(* (+ (2) (3)) (- (7) (8))))
2. Trace: (BIN-TREE-POSTORDER '(+ (2) (3)))
3. Trace: (BIN-TREE-POSTORDER '(2))
3. Trace: BIN-TREE-POSTORDER ==> (2)
3. Trace: (BIN-TREE-POSTORDER '(3))
3. Trace: BIN-TREE-POSTORDER ==> (3)
2. Trace: BIN-TREE-POSTORDER ==> ((2 3) . +)
2. Trace: (BIN-TREE-POSTORDER '(- (7) (8)))
3. Trace: (BIN-TREE-POSTORDER '(7))
3. Trace: BIN-TREE-POSTORDER ==> (7)
3. Trace: (BIN-TREE-POSTORDER '(8))
3. Trace: BIN-TREE-POSTORDER ==> (8)
2. Trace: BIN-TREE-POSTORDER ==> ((7 8) . -)
I've tried using list instead of cons, which provides a partially correct answer in the form of a list-of-lists:
(((2 3) + (7 8) -) *)
However, the correct answer is:
(2 3 + 7 8 - *)
Could anyone who answers provide hints or pointers, instead of modified code, so I could better understand the problem? I'd rather not look at the tutorial's answers, because that won't help me learn what I'm doing wrong.
Rest assured I will turn it into a tail-recursive function after the basic recursive function is figured out.
Thank you for anyone who can help!